dexbot 1.1.10
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/LICENSE +21 -0
- package/README.md +287 -0
- package/claw/README.md +513 -0
- package/claw/scripts/memu_runner.py +385 -0
- package/claw/skills/bitshares-guide/SKILL.md +14 -0
- package/claw/skills/bitshares-guide/references/example-skill-shells.md +18 -0
- package/claw/skills/bitshares-guide/references/presentation-patterns.md +19 -0
- package/claw/skills/bitshares-guide/references/scope-guardrails.md +9 -0
- package/claw/skills/launcher-ops/SKILL.md +18 -0
- package/claw/skills/launcher-ops/references/launcher-workflow.md +23 -0
- package/claw/skills/margin-trading/SKILL.md +23 -0
- package/claw/skills/margin-trading/references/honest-asset-list.md +74 -0
- package/claw/skills/margin-trading/references/honest-assets.md +44 -0
- package/claw/skills/margin-trading/references/position-management.md +203 -0
- package/claw/skills/margin-trading/references/trading-concepts.md +80 -0
- package/claw/skills/memu-memory/SKILL.md +218 -0
- package/claw/skills/shared/references/js-automation-overview.md +24 -0
- package/claw/skills/shared/references/safety-and-staleness.md +11 -0
- package/claw/skills/shared/references/skill-boundaries.md +17 -0
- package/claw/skills/trend-detection/SKILL.md +33 -0
- package/claw/skills/trend-detection/agents/openai.yaml +3 -0
- package/claw/skills/trend-detection/references/service.md +45 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts +3 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +149 -0
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +1 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts +3 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +387 -0
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +1 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts +3 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +200 -0
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +1 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts +3 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +212 -0
- package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +1 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +31 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +249 -0
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +1 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +2 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +1 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +782 -0
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +1 -0
- package/dist/analysis/analyze_derivatives.d.ts +95 -0
- package/dist/analysis/analyze_derivatives.d.ts.map +1 -0
- package/dist/analysis/analyze_derivatives.js +295 -0
- package/dist/analysis/analyze_derivatives.js.map +1 -0
- package/dist/analysis/analyze_dynamic_weight.d.ts +14 -0
- package/dist/analysis/analyze_dynamic_weight.d.ts.map +1 -0
- package/dist/analysis/analyze_dynamic_weight.js +208 -0
- package/dist/analysis/analyze_dynamic_weight.js.map +1 -0
- package/dist/analysis/analyze_kalman.d.ts +13 -0
- package/dist/analysis/analyze_kalman.d.ts.map +1 -0
- package/dist/analysis/analyze_kalman.js +123 -0
- package/dist/analysis/analyze_kalman.js.map +1 -0
- package/dist/analysis/analyze_regime.d.ts +20 -0
- package/dist/analysis/analyze_regime.d.ts.map +1 -0
- package/dist/analysis/analyze_regime.js +139 -0
- package/dist/analysis/analyze_regime.js.map +1 -0
- package/dist/analysis/analyze_regime_windows.d.ts +19 -0
- package/dist/analysis/analyze_regime_windows.d.ts.map +1 -0
- package/dist/analysis/analyze_regime_windows.js +413 -0
- package/dist/analysis/analyze_regime_windows.js.map +1 -0
- package/dist/analysis/analyze_risk_profile.d.ts +3 -0
- package/dist/analysis/analyze_risk_profile.d.ts.map +1 -0
- package/dist/analysis/analyze_risk_profile.js +159 -0
- package/dist/analysis/analyze_risk_profile.js.map +1 -0
- package/dist/analysis/analyze_trade_heatmap.d.ts +3 -0
- package/dist/analysis/analyze_trade_heatmap.d.ts.map +1 -0
- package/dist/analysis/analyze_trade_heatmap.js +367 -0
- package/dist/analysis/analyze_trade_heatmap.js.map +1 -0
- package/dist/analysis/analyze_volatility.d.ts +22 -0
- package/dist/analysis/analyze_volatility.d.ts.map +1 -0
- package/dist/analysis/analyze_volatility.js +172 -0
- package/dist/analysis/analyze_volatility.js.map +1 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +99 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +1 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +804 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +1 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +2 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +1 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +347 -0
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +1 -0
- package/dist/analysis/bot_fitting/shared_utils.d.ts +15 -0
- package/dist/analysis/bot_fitting/shared_utils.d.ts.map +1 -0
- package/dist/analysis/bot_fitting/shared_utils.js +48 -0
- package/dist/analysis/bot_fitting/shared_utils.js.map +1 -0
- package/dist/analysis/bot_key_utils.d.ts +16 -0
- package/dist/analysis/bot_key_utils.d.ts.map +1 -0
- package/dist/analysis/bot_key_utils.js +61 -0
- package/dist/analysis/bot_key_utils.js.map +1 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.d.ts +3 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +1 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.js +498 -0
- package/dist/analysis/bot_usage/discover_bot_accounts.js.map +1 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +546 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +1 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.js +427 -0
- package/dist/analysis/bot_usage/kibana_bot_queries.js.map +1 -0
- package/dist/analysis/chart_utils.d.ts +13 -0
- package/dist/analysis/chart_utils.d.ts.map +1 -0
- package/dist/analysis/chart_utils.js +142 -0
- package/dist/analysis/chart_utils.js.map +1 -0
- package/dist/analysis/derivative_chart_generator.d.ts +18 -0
- package/dist/analysis/derivative_chart_generator.d.ts.map +1 -0
- package/dist/analysis/derivative_chart_generator.js +896 -0
- package/dist/analysis/derivative_chart_generator.js.map +1 -0
- package/dist/analysis/math_utils.d.ts +35 -0
- package/dist/analysis/math_utils.d.ts.map +1 -0
- package/dist/analysis/math_utils.js +121 -0
- package/dist/analysis/math_utils.js.map +1 -0
- package/dist/analysis/price_sources.d.ts +34 -0
- package/dist/analysis/price_sources.d.ts.map +1 -0
- package/dist/analysis/price_sources.js +103 -0
- package/dist/analysis/price_sources.js.map +1 -0
- package/dist/analysis/trade_profitability.d.ts +115 -0
- package/dist/analysis/trade_profitability.d.ts.map +1 -0
- package/dist/analysis/trade_profitability.js +1247 -0
- package/dist/analysis/trade_profitability.js.map +1 -0
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +38 -0
- package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +1 -0
- package/dist/analysis/tradingview/analyze_tradingview.js +212 -0
- package/dist/analysis/tradingview/analyze_tradingview.js.map +1 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +9 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +1 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +1717 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/derivative_analyzer.d.ts +250 -0
- package/dist/analysis/trend_detection/derivative_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/derivative_analyzer.js +903 -0
- package/dist/analysis/trend_detection/derivative_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +1449 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/hurst_analyzer.d.ts +42 -0
- package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/hurst_analyzer.js +159 -0
- package/dist/analysis/trend_detection/hurst_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.js +408 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts +103 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.js +229 -0
- package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts +34 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +1 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.js +89 -0
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +1 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts +39 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +1 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.js +132 -0
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js +345 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +2 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js +130 -0
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +2 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +1 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +38 -0
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +1 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +6 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +1 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.js +732 -0
- package/dist/analysis/trend_detection/volatility_chart_generator.js.map +1 -0
- package/dist/bot.d.ts +49 -0
- package/dist/bot.d.ts.map +1 -0
- package/dist/bot.js +221 -0
- package/dist/bot.js.map +1 -0
- package/dist/credential-daemon.d.ts +64 -0
- package/dist/credential-daemon.d.ts.map +1 -0
- package/dist/credential-daemon.js +987 -0
- package/dist/credential-daemon.js.map +1 -0
- package/dist/dexbot.d.ts +87 -0
- package/dist/dexbot.d.ts.map +1 -0
- package/dist/dexbot.js +1222 -0
- package/dist/dexbot.js.map +1 -0
- package/dist/market_adapter/ama_signal_runner.d.ts +3 -0
- package/dist/market_adapter/ama_signal_runner.d.ts.map +1 -0
- package/dist/market_adapter/ama_signal_runner.js +175 -0
- package/dist/market_adapter/ama_signal_runner.js.map +1 -0
- package/dist/market_adapter/candle_utils.d.ts +57 -0
- package/dist/market_adapter/candle_utils.d.ts.map +1 -0
- package/dist/market_adapter/candle_utils.js +252 -0
- package/dist/market_adapter/candle_utils.js.map +1 -0
- package/dist/market_adapter/core/asymmetric_bounds.d.ts +20 -0
- package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +1 -0
- package/dist/market_adapter/core/asymmetric_bounds.js +88 -0
- package/dist/market_adapter/core/asymmetric_bounds.js.map +1 -0
- package/dist/market_adapter/core/config_normalizers.d.ts +10 -0
- package/dist/market_adapter/core/config_normalizers.d.ts.map +1 -0
- package/dist/market_adapter/core/config_normalizers.js +24 -0
- package/dist/market_adapter/core/config_normalizers.js.map +1 -0
- package/dist/market_adapter/core/kibana_candles.d.ts +74 -0
- package/dist/market_adapter/core/kibana_candles.d.ts.map +1 -0
- package/dist/market_adapter/core/kibana_candles.js +249 -0
- package/dist/market_adapter/core/kibana_candles.js.map +1 -0
- package/dist/market_adapter/core/kibana_client.d.ts +27 -0
- package/dist/market_adapter/core/kibana_client.d.ts.map +1 -0
- package/dist/market_adapter/core/kibana_client.js +120 -0
- package/dist/market_adapter/core/kibana_client.js.map +1 -0
- package/dist/market_adapter/core/kibana_market_candles.d.ts +143 -0
- package/dist/market_adapter/core/kibana_market_candles.d.ts.map +1 -0
- package/dist/market_adapter/core/kibana_market_candles.js +170 -0
- package/dist/market_adapter/core/kibana_market_candles.js.map +1 -0
- package/dist/market_adapter/core/market_adapter_service.d.ts +210 -0
- package/dist/market_adapter/core/market_adapter_service.d.ts.map +1 -0
- package/dist/market_adapter/core/market_adapter_service.js +2328 -0
- package/dist/market_adapter/core/market_adapter_service.js.map +1 -0
- package/dist/market_adapter/core/strategies/ama.d.ts +2 -0
- package/dist/market_adapter/core/strategies/ama.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/ama.js +138 -0
- package/dist/market_adapter/core/strategies/ama.js.map +1 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +50 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.js +143 -0
- package/dist/market_adapter/core/strategies/ama_slope_model.js.map +1 -0
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts +12 -0
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/atr/calculator.js +47 -0
- package/dist/market_adapter/core/strategies/atr/calculator.js.map +1 -0
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts +32 -0
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/collateral_manager.js +68 -0
- package/dist/market_adapter/core/strategies/collateral_manager.js.map +1 -0
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +66 -0
- package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +1 -0
- package/dist/market_adapter/core/strategies/regime_gate.js +189 -0
- package/dist/market_adapter/core/strategies/regime_gate.js.map +1 -0
- package/dist/market_adapter/index.d.ts +10 -0
- package/dist/market_adapter/index.d.ts.map +1 -0
- package/dist/market_adapter/index.js +71 -0
- package/dist/market_adapter/index.js.map +1 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts +3 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +1 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1165 -0
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +1 -0
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +54 -0
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +1 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js +743 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js.map +1 -0
- package/dist/market_adapter/inputs/kibana_source.d.ts +68 -0
- package/dist/market_adapter/inputs/kibana_source.d.ts.map +1 -0
- package/dist/market_adapter/inputs/kibana_source.js +143 -0
- package/dist/market_adapter/inputs/kibana_source.js.map +1 -0
- package/dist/market_adapter/interval_utils.d.ts +6 -0
- package/dist/market_adapter/interval_utils.d.ts.map +1 -0
- package/dist/market_adapter/interval_utils.js +14 -0
- package/dist/market_adapter/interval_utils.js.map +1 -0
- package/dist/market_adapter/log_format.d.ts +16 -0
- package/dist/market_adapter/log_format.d.ts.map +1 -0
- package/dist/market_adapter/log_format.js +72 -0
- package/dist/market_adapter/log_format.js.map +1 -0
- package/dist/market_adapter/lp_chart_core.d.ts +6 -0
- package/dist/market_adapter/lp_chart_core.d.ts.map +1 -0
- package/dist/market_adapter/lp_chart_core.js +874 -0
- package/dist/market_adapter/lp_chart_core.js.map +1 -0
- package/dist/market_adapter/lp_chart_runner.d.ts +135 -0
- package/dist/market_adapter/lp_chart_runner.d.ts.map +1 -0
- package/dist/market_adapter/lp_chart_runner.js +337 -0
- package/dist/market_adapter/lp_chart_runner.js.map +1 -0
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +23 -0
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +1 -0
- package/dist/market_adapter/lp_chart_strategy_loader.js +169 -0
- package/dist/market_adapter/lp_chart_strategy_loader.js.map +1 -0
- package/dist/market_adapter/market_adapter.d.ts +133 -0
- package/dist/market_adapter/market_adapter.d.ts.map +1 -0
- package/dist/market_adapter/market_adapter.js +1331 -0
- package/dist/market_adapter/market_adapter.js.map +1 -0
- package/dist/market_adapter/merge_lp_data.d.ts +3 -0
- package/dist/market_adapter/merge_lp_data.d.ts.map +1 -0
- package/dist/market_adapter/merge_lp_data.js +125 -0
- package/dist/market_adapter/merge_lp_data.js.map +1 -0
- package/dist/market_adapter/test_helpers.d.ts +14 -0
- package/dist/market_adapter/test_helpers.d.ts.map +1 -0
- package/dist/market_adapter/test_helpers.js +22 -0
- package/dist/market_adapter/test_helpers.js.map +1 -0
- package/dist/market_adapter/utils/adapter_client.d.ts +20 -0
- package/dist/market_adapter/utils/adapter_client.d.ts.map +1 -0
- package/dist/market_adapter/utils/adapter_client.js +88 -0
- package/dist/market_adapter/utils/adapter_client.js.map +1 -0
- package/dist/market_adapter/utils/atomic_write.d.ts +9 -0
- package/dist/market_adapter/utils/atomic_write.d.ts.map +1 -0
- package/dist/market_adapter/utils/atomic_write.js +13 -0
- package/dist/market_adapter/utils/atomic_write.js.map +1 -0
- package/dist/market_adapter/utils/chain.d.ts +50 -0
- package/dist/market_adapter/utils/chain.d.ts.map +1 -0
- package/dist/market_adapter/utils/chain.js +196 -0
- package/dist/market_adapter/utils/chain.js.map +1 -0
- package/dist/market_adapter/utils/data_discovery.d.ts +6 -0
- package/dist/market_adapter/utils/data_discovery.d.ts.map +1 -0
- package/dist/market_adapter/utils/data_discovery.js +35 -0
- package/dist/market_adapter/utils/data_discovery.js.map +1 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +15 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +1 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.js +60 -0
- package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +1 -0
- package/dist/market_adapter/utils/file_lock.d.ts +19 -0
- package/dist/market_adapter/utils/file_lock.d.ts.map +1 -0
- package/dist/market_adapter/utils/file_lock.js +191 -0
- package/dist/market_adapter/utils/file_lock.js.map +1 -0
- package/dist/market_adapter/utils/native_history.d.ts +19 -0
- package/dist/market_adapter/utils/native_history.d.ts.map +1 -0
- package/dist/market_adapter/utils/native_history.js +172 -0
- package/dist/market_adapter/utils/native_history.js.map +1 -0
- package/dist/market_adapter/utils/paths.d.ts +5 -0
- package/dist/market_adapter/utils/paths.d.ts.map +1 -0
- package/dist/market_adapter/utils/paths.js +7 -0
- package/dist/market_adapter/utils/paths.js.map +1 -0
- package/dist/modules/account_bots.d.ts +112 -0
- package/dist/modules/account_bots.d.ts.map +1 -0
- package/dist/modules/account_bots.js +1259 -0
- package/dist/modules/account_bots.js.map +1 -0
- package/dist/modules/account_orders.d.ts +273 -0
- package/dist/modules/account_orders.d.ts.map +1 -0
- package/dist/modules/account_orders.js +662 -0
- package/dist/modules/account_orders.js.map +1 -0
- package/dist/modules/authority_resolver.d.ts +2 -0
- package/dist/modules/authority_resolver.d.ts.map +1 -0
- package/dist/modules/authority_resolver.js +231 -0
- package/dist/modules/authority_resolver.js.map +1 -0
- package/dist/modules/bitshares-native/chain_client.d.ts +38 -0
- package/dist/modules/bitshares-native/chain_client.d.ts.map +1 -0
- package/dist/modules/bitshares-native/chain_client.js +322 -0
- package/dist/modules/bitshares-native/chain_client.js.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts +59 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.js +456 -0
- package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.d.ts +66 -0
- package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc.js +557 -0
- package/dist/modules/bitshares-native/crypto/ecc.js.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +1 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.js +20 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +1 -0
- package/dist/modules/bitshares-native/index.d.ts +3 -0
- package/dist/modules/bitshares-native/index.d.ts.map +1 -0
- package/dist/modules/bitshares-native/index.js +32 -0
- package/dist/modules/bitshares-native/index.js.map +1 -0
- package/dist/modules/bitshares-native/resolvers.d.ts +40 -0
- package/dist/modules/bitshares-native/resolvers.d.ts.map +1 -0
- package/dist/modules/bitshares-native/resolvers.js +161 -0
- package/dist/modules/bitshares-native/resolvers.js.map +1 -0
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +56 -0
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/chain_constants.js +92 -0
- package/dist/modules/bitshares-native/serial/chain_constants.js.map +1 -0
- package/dist/modules/bitshares-native/serial/index.d.ts +10 -0
- package/dist/modules/bitshares-native/serial/index.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/index.js +14 -0
- package/dist/modules/bitshares-native/serial/index.js.map +1 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts +102 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/operations.js +615 -0
- package/dist/modules/bitshares-native/serial/operations.js.map +1 -0
- package/dist/modules/bitshares-native/serial/serializer.d.ts +64 -0
- package/dist/modules/bitshares-native/serial/serializer.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/serializer.js +252 -0
- package/dist/modules/bitshares-native/serial/serializer.js.map +1 -0
- package/dist/modules/bitshares-native/serial/types.d.ts +120 -0
- package/dist/modules/bitshares-native/serial/types.d.ts.map +1 -0
- package/dist/modules/bitshares-native/serial/types.js +837 -0
- package/dist/modules/bitshares-native/serial/types.js.map +1 -0
- package/dist/modules/bitshares-native/signing_client.d.ts +6 -0
- package/dist/modules/bitshares-native/signing_client.d.ts.map +1 -0
- package/dist/modules/bitshares-native/signing_client.js +141 -0
- package/dist/modules/bitshares-native/signing_client.js.map +1 -0
- package/dist/modules/bitshares-native/subscriptions.d.ts +6 -0
- package/dist/modules/bitshares-native/subscriptions.d.ts.map +1 -0
- package/dist/modules/bitshares-native/subscriptions.js +865 -0
- package/dist/modules/bitshares-native/subscriptions.js.map +1 -0
- package/dist/modules/bitshares-native/transport.d.ts +51 -0
- package/dist/modules/bitshares-native/transport.d.ts.map +1 -0
- package/dist/modules/bitshares-native/transport.js +447 -0
- package/dist/modules/bitshares-native/transport.js.map +1 -0
- package/dist/modules/bitshares-native/tx/builder.d.ts +30 -0
- package/dist/modules/bitshares-native/tx/builder.d.ts.map +1 -0
- package/dist/modules/bitshares-native/tx/builder.js +262 -0
- package/dist/modules/bitshares-native/tx/builder.js.map +1 -0
- package/dist/modules/bitshares_client.d.ts +129 -0
- package/dist/modules/bitshares_client.d.ts.map +1 -0
- package/dist/modules/bitshares_client.js +627 -0
- package/dist/modules/bitshares_client.js.map +1 -0
- package/dist/modules/bot_settings.d.ts +33 -0
- package/dist/modules/bot_settings.d.ts.map +1 -0
- package/dist/modules/bot_settings.js +328 -0
- package/dist/modules/bot_settings.js.map +1 -0
- package/dist/modules/bots_file_lock.d.ts +88 -0
- package/dist/modules/bots_file_lock.d.ts.map +1 -0
- package/dist/modules/bots_file_lock.js +161 -0
- package/dist/modules/bots_file_lock.js.map +1 -0
- package/dist/modules/chain_keys.d.ts +302 -0
- package/dist/modules/chain_keys.d.ts.map +1 -0
- package/dist/modules/chain_keys.js +1095 -0
- package/dist/modules/chain_keys.js.map +1 -0
- package/dist/modules/chain_orders.d.ts +423 -0
- package/dist/modules/chain_orders.d.ts.map +1 -0
- package/dist/modules/chain_orders.js +1201 -0
- package/dist/modules/chain_orders.js.map +1 -0
- package/dist/modules/cli_whitelist_args.d.ts +6 -0
- package/dist/modules/cli_whitelist_args.d.ts.map +1 -0
- package/dist/modules/cli_whitelist_args.js +13 -0
- package/dist/modules/cli_whitelist_args.js.map +1 -0
- package/dist/modules/config.d.ts +57 -0
- package/dist/modules/config.d.ts.map +1 -0
- package/dist/modules/config.js +107 -0
- package/dist/modules/config.js.map +1 -0
- package/dist/modules/constants.d.ts +635 -0
- package/dist/modules/constants.d.ts.map +1 -0
- package/dist/modules/constants.js +1464 -0
- package/dist/modules/constants.js.map +1 -0
- package/dist/modules/cr_planner.d.ts +51 -0
- package/dist/modules/cr_planner.d.ts.map +1 -0
- package/dist/modules/cr_planner.js +299 -0
- package/dist/modules/cr_planner.js.map +1 -0
- package/dist/modules/credential_policy.d.ts +188 -0
- package/dist/modules/credential_policy.d.ts.map +1 -0
- package/dist/modules/credential_policy.js +1452 -0
- package/dist/modules/credential_policy.js.map +1 -0
- package/dist/modules/credential_runtime.d.ts +42 -0
- package/dist/modules/credential_runtime.d.ts.map +1 -0
- package/dist/modules/credential_runtime.js +148 -0
- package/dist/modules/credential_runtime.js.map +1 -0
- package/dist/modules/credential_session_cache.d.ts +36 -0
- package/dist/modules/credential_session_cache.d.ts.map +1 -0
- package/dist/modules/credential_session_cache.js +106 -0
- package/dist/modules/credential_session_cache.js.map +1 -0
- package/dist/modules/credit_runtime.d.ts +412 -0
- package/dist/modules/credit_runtime.d.ts.map +1 -0
- package/dist/modules/credit_runtime.js +2866 -0
- package/dist/modules/credit_runtime.js.map +1 -0
- package/dist/modules/crypto/browser_provider.d.ts +15 -0
- package/dist/modules/crypto/browser_provider.d.ts.map +1 -0
- package/dist/modules/crypto/browser_provider.js +113 -0
- package/dist/modules/crypto/browser_provider.js.map +1 -0
- package/dist/modules/crypto/index.d.ts +9 -0
- package/dist/modules/crypto/index.d.ts.map +1 -0
- package/dist/modules/crypto/index.js +44 -0
- package/dist/modules/crypto/index.js.map +1 -0
- package/dist/modules/crypto/node_provider.d.ts +15 -0
- package/dist/modules/crypto/node_provider.d.ts.map +1 -0
- package/dist/modules/crypto/node_provider.js +74 -0
- package/dist/modules/crypto/node_provider.js.map +1 -0
- package/dist/modules/crypto/provider.d.ts +34 -0
- package/dist/modules/crypto/provider.d.ts.map +1 -0
- package/dist/modules/crypto/provider.js +3 -0
- package/dist/modules/crypto/provider.js.map +1 -0
- package/dist/modules/crypto/pure_ripemd160.d.ts +8 -0
- package/dist/modules/crypto/pure_ripemd160.d.ts.map +1 -0
- package/dist/modules/crypto/pure_ripemd160.js +142 -0
- package/dist/modules/crypto/pure_ripemd160.js.map +1 -0
- package/dist/modules/crypto/pure_scrypt.d.ts +23 -0
- package/dist/modules/crypto/pure_scrypt.d.ts.map +1 -0
- package/dist/modules/crypto/pure_scrypt.js +161 -0
- package/dist/modules/crypto/pure_scrypt.js.map +1 -0
- package/dist/modules/crypto/pure_secp256k1.d.ts +29 -0
- package/dist/modules/crypto/pure_secp256k1.d.ts.map +1 -0
- package/dist/modules/crypto/pure_secp256k1.js +195 -0
- package/dist/modules/crypto/pure_secp256k1.js.map +1 -0
- package/dist/modules/crypto/sync.d.ts +13 -0
- package/dist/modules/crypto/sync.d.ts.map +1 -0
- package/dist/modules/crypto/sync.js +37 -0
- package/dist/modules/crypto/sync.js.map +1 -0
- package/dist/modules/dexbot_class.d.ts +1074 -0
- package/dist/modules/dexbot_class.d.ts.map +1 -0
- package/dist/modules/dexbot_class.js +4613 -0
- package/dist/modules/dexbot_class.js.map +1 -0
- package/dist/modules/dexbot_credential_client.d.ts +71 -0
- package/dist/modules/dexbot_credential_client.d.ts.map +1 -0
- package/dist/modules/dexbot_credential_client.js +224 -0
- package/dist/modules/dexbot_credential_client.js.map +1 -0
- package/dist/modules/dexbot_fill_runtime.d.ts +173 -0
- package/dist/modules/dexbot_fill_runtime.d.ts.map +1 -0
- package/dist/modules/dexbot_fill_runtime.js +217 -0
- package/dist/modules/dexbot_fill_runtime.js.map +1 -0
- package/dist/modules/dexbot_maintenance_runtime.d.ts +279 -0
- package/dist/modules/dexbot_maintenance_runtime.d.ts.map +1 -0
- package/dist/modules/dexbot_maintenance_runtime.js +1613 -0
- package/dist/modules/dexbot_maintenance_runtime.js.map +1 -0
- package/dist/modules/env.d.ts +12 -0
- package/dist/modules/env.d.ts.map +1 -0
- package/dist/modules/env.js +57 -0
- package/dist/modules/env.js.map +1 -0
- package/dist/modules/fund_registry.d.ts +96 -0
- package/dist/modules/fund_registry.d.ts.map +1 -0
- package/dist/modules/fund_registry.js +261 -0
- package/dist/modules/fund_registry.js.map +1 -0
- package/dist/modules/general_settings.d.ts +36 -0
- package/dist/modules/general_settings.d.ts.map +1 -0
- package/dist/modules/general_settings.js +63 -0
- package/dist/modules/general_settings.js.map +1 -0
- package/dist/modules/graceful_shutdown.d.ts +86 -0
- package/dist/modules/graceful_shutdown.d.ts.map +1 -0
- package/dist/modules/graceful_shutdown.js +164 -0
- package/dist/modules/graceful_shutdown.js.map +1 -0
- package/dist/modules/key_store.d.ts +60 -0
- package/dist/modules/key_store.d.ts.map +1 -0
- package/dist/modules/key_store.js +215 -0
- package/dist/modules/key_store.js.map +1 -0
- package/dist/modules/launcher/bot_supervisor.d.ts +84 -0
- package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -0
- package/dist/modules/launcher/bot_supervisor.js +1067 -0
- package/dist/modules/launcher/bot_supervisor.js.map +1 -0
- package/dist/modules/launcher/child_env.d.ts +9 -0
- package/dist/modules/launcher/child_env.d.ts.map +1 -0
- package/dist/modules/launcher/child_env.js +78 -0
- package/dist/modules/launcher/child_env.js.map +1 -0
- package/dist/modules/launcher/credential_bootstrap.d.ts +22 -0
- package/dist/modules/launcher/credential_bootstrap.d.ts.map +1 -0
- package/dist/modules/launcher/credential_bootstrap.js +303 -0
- package/dist/modules/launcher/credential_bootstrap.js.map +1 -0
- package/dist/modules/launcher/credential_daemon.d.ts +32 -0
- package/dist/modules/launcher/credential_daemon.d.ts.map +1 -0
- package/dist/modules/launcher/credential_daemon.js +173 -0
- package/dist/modules/launcher/credential_daemon.js.map +1 -0
- package/dist/modules/launcher/credential_secret.d.ts +6 -0
- package/dist/modules/launcher/credential_secret.d.ts.map +1 -0
- package/dist/modules/launcher/credential_secret.js +15 -0
- package/dist/modules/launcher/credential_secret.js.map +1 -0
- package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -0
- package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -0
- package/dist/modules/launcher/foreign_cred_daemon.js +166 -0
- package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -0
- package/dist/modules/launcher/headless_password.d.ts +8 -0
- package/dist/modules/launcher/headless_password.d.ts.map +1 -0
- package/dist/modules/launcher/headless_password.js +33 -0
- package/dist/modules/launcher/headless_password.js.map +1 -0
- package/dist/modules/launcher/launch_modes.d.ts +36 -0
- package/dist/modules/launcher/launch_modes.d.ts.map +1 -0
- package/dist/modules/launcher/launch_modes.js +129 -0
- package/dist/modules/launcher/launch_modes.js.map +1 -0
- package/dist/modules/launcher/market_adapter_runtime.d.ts +43 -0
- package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -0
- package/dist/modules/launcher/market_adapter_runtime.js +217 -0
- package/dist/modules/launcher/market_adapter_runtime.js.map +1 -0
- package/dist/modules/launcher/market_adapter_watchdog.d.ts +26 -0
- package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +1 -0
- package/dist/modules/launcher/market_adapter_watchdog.js +214 -0
- package/dist/modules/launcher/market_adapter_watchdog.js.map +1 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts +89 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -0
- package/dist/modules/launcher/monolithic_runtime.js +425 -0
- package/dist/modules/launcher/monolithic_runtime.js.map +1 -0
- package/dist/modules/launcher/runtime_entry.d.ts +26 -0
- package/dist/modules/launcher/runtime_entry.d.ts.map +1 -0
- package/dist/modules/launcher/runtime_entry.js +49 -0
- package/dist/modules/launcher/runtime_entry.js.map +1 -0
- package/dist/modules/launcher/status_reporting.d.ts +48 -0
- package/dist/modules/launcher/status_reporting.d.ts.map +1 -0
- package/dist/modules/launcher/status_reporting.js +113 -0
- package/dist/modules/launcher/status_reporting.js.map +1 -0
- package/dist/modules/launcher/supervisor_control.d.ts +6 -0
- package/dist/modules/launcher/supervisor_control.d.ts.map +1 -0
- package/dist/modules/launcher/supervisor_control.js +59 -0
- package/dist/modules/launcher/supervisor_control.js.map +1 -0
- package/dist/modules/logger.d.ts +2 -0
- package/dist/modules/logger.d.ts.map +1 -0
- package/dist/modules/logger.js +71 -0
- package/dist/modules/logger.js.map +1 -0
- package/dist/modules/market_adapter_whitelist.d.ts +22 -0
- package/dist/modules/market_adapter_whitelist.d.ts.map +1 -0
- package/dist/modules/market_adapter_whitelist.js +82 -0
- package/dist/modules/market_adapter_whitelist.js.map +1 -0
- package/dist/modules/node_health_cache.d.ts +55 -0
- package/dist/modules/node_health_cache.d.ts.map +1 -0
- package/dist/modules/node_health_cache.js +134 -0
- package/dist/modules/node_health_cache.js.map +1 -0
- package/dist/modules/node_manager.d.ts +215 -0
- package/dist/modules/node_manager.d.ts.map +1 -0
- package/dist/modules/node_manager.js +628 -0
- package/dist/modules/node_manager.js.map +1 -0
- package/dist/modules/order/accounting.d.ts +349 -0
- package/dist/modules/order/accounting.d.ts.map +1 -0
- package/dist/modules/order/accounting.js +1191 -0
- package/dist/modules/order/accounting.js.map +1 -0
- package/dist/modules/order/async_lock.d.ts +126 -0
- package/dist/modules/order/async_lock.d.ts.map +1 -0
- package/dist/modules/order/async_lock.js +195 -0
- package/dist/modules/order/async_lock.js.map +1 -0
- package/dist/modules/order/export.d.ts +129 -0
- package/dist/modules/order/export.d.ts.map +1 -0
- package/dist/modules/order/export.js +316 -0
- package/dist/modules/order/export.js.map +1 -0
- package/dist/modules/order/format.d.ts +158 -0
- package/dist/modules/order/format.d.ts.map +1 -0
- package/dist/modules/order/format.js +232 -0
- package/dist/modules/order/format.js.map +1 -0
- package/dist/modules/order/grid.d.ts +549 -0
- package/dist/modules/order/grid.d.ts.map +1 -0
- package/dist/modules/order/grid.js +1746 -0
- package/dist/modules/order/grid.js.map +1 -0
- package/dist/modules/order/grid_reconcile.d.ts +154 -0
- package/dist/modules/order/grid_reconcile.d.ts.map +1 -0
- package/dist/modules/order/grid_reconcile.js +1192 -0
- package/dist/modules/order/grid_reconcile.js.map +1 -0
- package/dist/modules/order/index.d.ts +55 -0
- package/dist/modules/order/index.d.ts.map +1 -0
- package/dist/modules/order/index.js +79 -0
- package/dist/modules/order/index.js.map +1 -0
- package/dist/modules/order/logger.d.ts +136 -0
- package/dist/modules/order/logger.d.ts.map +1 -0
- package/dist/modules/order/logger.js +614 -0
- package/dist/modules/order/logger.js.map +1 -0
- package/dist/modules/order/logger_state.d.ts +133 -0
- package/dist/modules/order/logger_state.d.ts.map +1 -0
- package/dist/modules/order/logger_state.js +170 -0
- package/dist/modules/order/logger_state.js.map +1 -0
- package/dist/modules/order/manager.d.ts +413 -0
- package/dist/modules/order/manager.d.ts.map +1 -0
- package/dist/modules/order/manager.js +1605 -0
- package/dist/modules/order/manager.js.map +1 -0
- package/dist/modules/order/processed_fill_store.d.ts +135 -0
- package/dist/modules/order/processed_fill_store.d.ts.map +1 -0
- package/dist/modules/order/processed_fill_store.js +288 -0
- package/dist/modules/order/processed_fill_store.js.map +1 -0
- package/dist/modules/order/runner.d.ts +70 -0
- package/dist/modules/order/runner.d.ts.map +1 -0
- package/dist/modules/order/runner.js +140 -0
- package/dist/modules/order/runner.js.map +1 -0
- package/dist/modules/order/strategy.d.ts +196 -0
- package/dist/modules/order/strategy.d.ts.map +1 -0
- package/dist/modules/order/strategy.js +398 -0
- package/dist/modules/order/strategy.js.map +1 -0
- package/dist/modules/order/sync_engine.d.ts +386 -0
- package/dist/modules/order/sync_engine.d.ts.map +1 -0
- package/dist/modules/order/sync_engine.js +1459 -0
- package/dist/modules/order/sync_engine.js.map +1 -0
- package/dist/modules/order/utils/math.d.ts +677 -0
- package/dist/modules/order/utils/math.d.ts.map +1 -0
- package/dist/modules/order/utils/math.js +1172 -0
- package/dist/modules/order/utils/math.js.map +1 -0
- package/dist/modules/order/utils/order.d.ts +572 -0
- package/dist/modules/order/utils/order.d.ts.map +1 -0
- package/dist/modules/order/utils/order.js +1145 -0
- package/dist/modules/order/utils/order.js.map +1 -0
- package/dist/modules/order/utils/system.d.ts +268 -0
- package/dist/modules/order/utils/system.d.ts.map +1 -0
- package/dist/modules/order/utils/system.js +1261 -0
- package/dist/modules/order/utils/system.js.map +1 -0
- package/dist/modules/order/utils/validate.d.ts +280 -0
- package/dist/modules/order/utils/validate.d.ts.map +1 -0
- package/dist/modules/order/utils/validate.js +918 -0
- package/dist/modules/order/utils/validate.js.map +1 -0
- package/dist/modules/order/working_grid.d.ts +212 -0
- package/dist/modules/order/working_grid.d.ts.map +1 -0
- package/dist/modules/order/working_grid.js +279 -0
- package/dist/modules/order/working_grid.js.map +1 -0
- package/dist/modules/path_api.d.ts +32 -0
- package/dist/modules/path_api.d.ts.map +1 -0
- package/dist/modules/path_api.js +148 -0
- package/dist/modules/path_api.js.map +1 -0
- package/dist/modules/paths.d.ts +58 -0
- package/dist/modules/paths.d.ts.map +1 -0
- package/dist/modules/paths.js +82 -0
- package/dist/modules/paths.js.map +1 -0
- package/dist/modules/process_discovery.d.ts +58 -0
- package/dist/modules/process_discovery.d.ts.map +1 -0
- package/dist/modules/process_discovery.js +265 -0
- package/dist/modules/process_discovery.js.map +1 -0
- package/dist/modules/runtime.d.ts +34 -0
- package/dist/modules/runtime.d.ts.map +1 -0
- package/dist/modules/runtime.js +98 -0
- package/dist/modules/runtime.js.map +1 -0
- package/dist/modules/runtime_settings.d.ts +12 -0
- package/dist/modules/runtime_settings.d.ts.map +1 -0
- package/dist/modules/runtime_settings.js +122 -0
- package/dist/modules/runtime_settings.js.map +1 -0
- package/dist/modules/settings_merge.d.ts +38 -0
- package/dist/modules/settings_merge.d.ts.map +1 -0
- package/dist/modules/settings_merge.js +246 -0
- package/dist/modules/settings_merge.js.map +1 -0
- package/dist/modules/storage/browser_adapter.d.ts +56 -0
- package/dist/modules/storage/browser_adapter.d.ts.map +1 -0
- package/dist/modules/storage/browser_adapter.js +231 -0
- package/dist/modules/storage/browser_adapter.js.map +1 -0
- package/dist/modules/storage/index.d.ts +28 -0
- package/dist/modules/storage/index.d.ts.map +1 -0
- package/dist/modules/storage/index.js +52 -0
- package/dist/modules/storage/index.js.map +1 -0
- package/dist/modules/storage/node_adapter.d.ts +49 -0
- package/dist/modules/storage/node_adapter.d.ts.map +1 -0
- package/dist/modules/storage/node_adapter.js +167 -0
- package/dist/modules/storage/node_adapter.js.map +1 -0
- package/dist/modules/storage/types.d.ts +92 -0
- package/dist/modules/storage/types.d.ts.map +1 -0
- package/dist/modules/storage/types.js +3 -0
- package/dist/modules/storage/types.js.map +1 -0
- package/dist/modules/types.d.ts +1382 -0
- package/dist/modules/types.d.ts.map +1 -0
- package/dist/modules/types.js +11 -0
- package/dist/modules/types.js.map +1 -0
- package/dist/modules/utils/base58check.d.ts +12 -0
- package/dist/modules/utils/base58check.d.ts.map +1 -0
- package/dist/modules/utils/base58check.js +112 -0
- package/dist/modules/utils/base58check.js.map +1 -0
- package/dist/modules/utils/build_dir.d.ts +7 -0
- package/dist/modules/utils/build_dir.d.ts.map +1 -0
- package/dist/modules/utils/build_dir.js +8 -0
- package/dist/modules/utils/build_dir.js.map +1 -0
- package/dist/modules/utils/fs_utils.d.ts +25 -0
- package/dist/modules/utils/fs_utils.d.ts.map +1 -0
- package/dist/modules/utils/fs_utils.js +27 -0
- package/dist/modules/utils/fs_utils.js.map +1 -0
- package/dist/modules/utils/math_utils.d.ts +10 -0
- package/dist/modules/utils/math_utils.d.ts.map +1 -0
- package/dist/modules/utils/math_utils.js +17 -0
- package/dist/modules/utils/math_utils.js.map +1 -0
- package/dist/modules/validate_profiles.d.ts +37 -0
- package/dist/modules/validate_profiles.d.ts.map +1 -0
- package/dist/modules/validate_profiles.js +369 -0
- package/dist/modules/validate_profiles.js.map +1 -0
- package/dist/pm2.d.ts +167 -0
- package/dist/pm2.d.ts.map +1 -0
- package/dist/pm2.js +998 -0
- package/dist/pm2.js.map +1 -0
- package/dist/scripts/analyze-git.d.ts +11 -0
- package/dist/scripts/analyze-git.d.ts.map +1 -0
- package/dist/scripts/analyze-git.js +851 -0
- package/dist/scripts/analyze-git.js.map +1 -0
- package/dist/scripts/analyze-orders.d.ts +17 -0
- package/dist/scripts/analyze-orders.d.ts.map +1 -0
- package/dist/scripts/analyze-orders.js +1568 -0
- package/dist/scripts/analyze-orders.js.map +1 -0
- package/dist/scripts/diagnose-kibana-candles.d.ts +3 -0
- package/dist/scripts/diagnose-kibana-candles.d.ts.map +1 -0
- package/dist/scripts/diagnose-kibana-candles.js +82 -0
- package/dist/scripts/diagnose-kibana-candles.js.map +1 -0
- package/dist/scripts/diagnose-pool-history.d.ts +3 -0
- package/dist/scripts/diagnose-pool-history.d.ts.map +1 -0
- package/dist/scripts/diagnose-pool-history.js +296 -0
- package/dist/scripts/diagnose-pool-history.js.map +1 -0
- package/dist/scripts/divergence-calc.d.ts +26 -0
- package/dist/scripts/divergence-calc.d.ts.map +1 -0
- package/dist/scripts/divergence-calc.js +119 -0
- package/dist/scripts/divergence-calc.js.map +1 -0
- package/dist/scripts/generate_lp_chart.d.ts +31 -0
- package/dist/scripts/generate_lp_chart.d.ts.map +1 -0
- package/dist/scripts/generate_lp_chart.js +92 -0
- package/dist/scripts/generate_lp_chart.js.map +1 -0
- package/dist/scripts/generate_mainnet_corpus_report.d.ts +24 -0
- package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +1 -0
- package/dist/scripts/generate_mainnet_corpus_report.js +237 -0
- package/dist/scripts/generate_mainnet_corpus_report.js.map +1 -0
- package/dist/scripts/generate_market_adapter_whitelist.d.ts +2 -0
- package/dist/scripts/generate_market_adapter_whitelist.d.ts.map +1 -0
- package/dist/scripts/generate_market_adapter_whitelist.js +111 -0
- package/dist/scripts/generate_market_adapter_whitelist.js.map +1 -0
- package/dist/scripts/migrate_bot_keys.d.ts +6 -0
- package/dist/scripts/migrate_bot_keys.d.ts.map +1 -0
- package/dist/scripts/migrate_bot_keys.js +301 -0
- package/dist/scripts/migrate_bot_keys.js.map +1 -0
- package/dist/scripts/native_release_gates.d.ts +3 -0
- package/dist/scripts/native_release_gates.d.ts.map +1 -0
- package/dist/scripts/native_release_gates.js +52 -0
- package/dist/scripts/native_release_gates.js.map +1 -0
- package/dist/scripts/print_grid.d.ts +16 -0
- package/dist/scripts/print_grid.d.ts.map +1 -0
- package/dist/scripts/print_grid.js +80 -0
- package/dist/scripts/print_grid.js.map +1 -0
- package/dist/scripts/run-tests.d.ts +2 -0
- package/dist/scripts/run-tests.d.ts.map +1 -0
- package/dist/scripts/run-tests.js +49 -0
- package/dist/scripts/run-tests.js.map +1 -0
- package/dist/scripts/sync-version.d.ts +14 -0
- package/dist/scripts/sync-version.d.ts.map +1 -0
- package/dist/scripts/sync-version.js +158 -0
- package/dist/scripts/sync-version.js.map +1 -0
- package/dist/scripts/test-credit-renewal.d.ts +2 -0
- package/dist/scripts/test-credit-renewal.d.ts.map +1 -0
- package/dist/scripts/test-credit-renewal.js +329 -0
- package/dist/scripts/test-credit-renewal.js.map +1 -0
- package/dist/scripts/update.d.ts +24 -0
- package/dist/scripts/update.d.ts.map +1 -0
- package/dist/scripts/update.js +650 -0
- package/dist/scripts/update.js.map +1 -0
- package/dist/scripts/validate_bots.d.ts +16 -0
- package/dist/scripts/validate_bots.d.ts.map +1 -0
- package/dist/scripts/validate_bots.js +106 -0
- package/dist/scripts/validate_bots.js.map +1 -0
- package/dist/scripts/verify-browser-bundle.d.ts +22 -0
- package/dist/scripts/verify-browser-bundle.d.ts.map +1 -0
- package/dist/scripts/verify-browser-bundle.js +339 -0
- package/dist/scripts/verify-browser-bundle.js.map +1 -0
- package/dist/unlock.d.ts +48 -0
- package/dist/unlock.d.ts.map +1 -0
- package/dist/unlock.js +925 -0
- package/dist/unlock.js.map +1 -0
- package/package.json +112 -0
- package/scripts/README.md +356 -0
- package/scripts/clear-all.sh +195 -0
- package/scripts/clear-logs.sh +95 -0
- package/scripts/clear-market-adapter.sh +196 -0
- package/scripts/clear-orders.sh +113 -0
- package/scripts/create-bot-symlinks.sh +51 -0
- package/scripts/postinstall.js +9 -0
- package/scripts/reset-settings.sh +118 -0
|
@@ -0,0 +1,1172 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* modules/order/utils/math.ts - Mathematical and Numeric Utilities
|
|
4
|
+
*
|
|
5
|
+
* Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
|
|
6
|
+
*
|
|
7
|
+
* ===============================================================================
|
|
8
|
+
* TABLE OF CONTENTS (42 exported functions)
|
|
9
|
+
* ===============================================================================
|
|
10
|
+
*
|
|
11
|
+
* SECTION 1: PARSING & VALIDATION (4 functions)
|
|
12
|
+
* - isExplicitZeroAllocation(value) - Check if value is explicitly zero
|
|
13
|
+
* - isPercentageString(v) - Check if value is percentage string
|
|
14
|
+
* - parsePercentageString(v) - Parse percentage string to decimal
|
|
15
|
+
* - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
|
|
16
|
+
*
|
|
17
|
+
* SECTION 2: FUND CALCULATIONS (4 functions)
|
|
18
|
+
* - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
|
|
19
|
+
* - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
|
|
20
|
+
* - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
|
|
21
|
+
* - resolveConfigValue(value, total) - Resolve percentage or absolute config value
|
|
22
|
+
*
|
|
23
|
+
* SECTION 3: BLOCKCHAIN CONVERSIONS (5 functions)
|
|
24
|
+
* - blockchainToFloat(intValue, precision) - Convert blockchain int to float
|
|
25
|
+
* - floatToBlockchainInt(floatValue, precision) - Convert float to blockchain int
|
|
26
|
+
* - quantizeFloat(value, precision) - Round float to blockchain precision
|
|
27
|
+
* - normalizeInt(value, precision) - Normalize int within precision bounds
|
|
28
|
+
* - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
|
|
29
|
+
*
|
|
30
|
+
* SECTION 4: PRECISION UTILITIES (5 functions)
|
|
31
|
+
* - getPrecision(assets, orderType) - Get precision for order type
|
|
32
|
+
* - getPrecisionByOrderType(assets, orderType) - Alias for getPrecision
|
|
33
|
+
* - getPrecisionForSide(assets, side) - Get precision by side (buy/sell)
|
|
34
|
+
* - getPrecisionsForManager(manager) - Get both asset precisions
|
|
35
|
+
* - getPrecisionSlack(precision) - Calculate tolerance for precision
|
|
36
|
+
*
|
|
37
|
+
* SECTION 5: ORDER SIZE VALIDATION (7 functions)
|
|
38
|
+
* - calculatePriceTolerance(price, size, type, assets) - Calculate price match tolerance
|
|
39
|
+
* - validateOrderAmountsWithinLimits(amountToSell, minToReceive) - Validate order limits
|
|
40
|
+
* - getMinOrderSize(assets, type) - Get minimum order size for type
|
|
41
|
+
* - getDustThresholdFactor() - Get dust threshold multiplier
|
|
42
|
+
* - getSingleDustThreshold(idealSize, dustThresholdPercent) - Get single dust threshold
|
|
43
|
+
* - getDoubleDustThreshold(idealSize, dustThresholdPercent) - Get double dust threshold
|
|
44
|
+
* - getMinAbsoluteOrderSize(orderType, assets, minFactor) - Get minimum absolute order size
|
|
45
|
+
* - validateOrderSize(manager, size, type, context) - Validate order size against minimums
|
|
46
|
+
*
|
|
47
|
+
* SECTION 6: FEE CALCULATIONS (2 functions + 2 internal)
|
|
48
|
+
* - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
|
|
49
|
+
* - _setFeeCache(cache) - Set internal fee cache (internal)
|
|
50
|
+
* - _getFeeCache() - Get internal fee cache (internal)
|
|
51
|
+
*
|
|
52
|
+
* SECTION 7: FUND ALLOCATION (6 functions)
|
|
53
|
+
* - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
|
|
54
|
+
* - cloneWeightDistribution(weightDistribution, base) - Clone weight distribution safely
|
|
55
|
+
* - calculateOrderSizes(manager, orderType) - Calculate order sizes for placement
|
|
56
|
+
* - calculateRotationOrderSizes(manager, orderType, fillAmount) - Calculate rotation sizes
|
|
57
|
+
* - calculateGridSideDivergenceMetric(manager, orderType, threshold) - Calculate divergence
|
|
58
|
+
* - clamp(value, min, max) - Clamp a value between min and max bounds
|
|
59
|
+
*
|
|
60
|
+
* SECTION 8: FEE DEDUCTION (3 functions)
|
|
61
|
+
* - calculateOrderCreationFees(count, btsFeeData) - Calculate total creation fees
|
|
62
|
+
* - deductOrderFeesFromFunds(available, count, btsFeeData, btsSide) - Deduct fees from funds
|
|
63
|
+
* - calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) - AMM swap math
|
|
64
|
+
*
|
|
65
|
+
* SECTION 9: GRID UTILITIES (1 function)
|
|
66
|
+
* - calculateGapSlots(incrementPercent, targetSpreadPercent) - Calculate gap slots count
|
|
67
|
+
*
|
|
68
|
+
* ===============================================================================
|
|
69
|
+
*/
|
|
70
|
+
const { ORDER_TYPES, FEE_PARAMETERS, DEFAULT_CONFIG, BTS_PRECISION, GRID_LIMITS } = require('../../constants');
|
|
71
|
+
const Format = require('../format');
|
|
72
|
+
const { isValidNumber, toFiniteNumber, isNumeric } = Format;
|
|
73
|
+
const Logger = require('../../logger');
|
|
74
|
+
const mathLogger = new Logger('Math');
|
|
75
|
+
const fundRegistry = require('../../fund_registry');
|
|
76
|
+
const MAX_INT64 = 9223372036854775807;
|
|
77
|
+
const MIN_INT64 = -9223372036854775808;
|
|
78
|
+
// ================================================================================
|
|
79
|
+
// SECTION 1: PARSING & VALIDATION
|
|
80
|
+
// ================================================================================
|
|
81
|
+
/**
|
|
82
|
+
* Check if a value is explicitly set to zero (number 0, string "0", or "0%").
|
|
83
|
+
* Used to distinguish between "not set" and "explicitly disabled".
|
|
84
|
+
*
|
|
85
|
+
* @param {*} value - Value to check
|
|
86
|
+
* @returns {boolean} True if value is explicitly zero
|
|
87
|
+
*/
|
|
88
|
+
function isExplicitZeroAllocation(value) {
|
|
89
|
+
if (typeof value === 'number')
|
|
90
|
+
return value === 0;
|
|
91
|
+
if (typeof value !== 'string')
|
|
92
|
+
return false;
|
|
93
|
+
const trimmed = value.trim();
|
|
94
|
+
if (trimmed === '')
|
|
95
|
+
return false;
|
|
96
|
+
if (trimmed.endsWith('%')) {
|
|
97
|
+
const percent = parseFloat(trimmed.slice(0, -1));
|
|
98
|
+
return Number.isFinite(percent) && percent === 0;
|
|
99
|
+
}
|
|
100
|
+
const numeric = parseFloat(trimmed);
|
|
101
|
+
return Number.isFinite(numeric) && numeric === 0;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Check if a value is a percentage string (ends with '%').
|
|
105
|
+
*
|
|
106
|
+
* @param {*} v - Value to test
|
|
107
|
+
* @returns {boolean} True if v is a string ending with '%'
|
|
108
|
+
*/
|
|
109
|
+
function isPercentageString(v) {
|
|
110
|
+
return typeof v === 'string' && v.trim().endsWith('%');
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Check if a value is a positive number.
|
|
114
|
+
*
|
|
115
|
+
* @param {*} value - Value to test
|
|
116
|
+
* @returns {boolean} True if the value is a finite number greater than 0
|
|
117
|
+
*/
|
|
118
|
+
function isPositiveNumber(value) {
|
|
119
|
+
const num = Number(value);
|
|
120
|
+
return Number.isFinite(num) && num > 0;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Check if a value is a positive number or a positive percentage string.
|
|
124
|
+
*
|
|
125
|
+
* @param {*} value - Value to test
|
|
126
|
+
* @returns {boolean} True if the value is a positive number or a percentage string like "25%"
|
|
127
|
+
*/
|
|
128
|
+
function isPositiveNumberOrPercent(value) {
|
|
129
|
+
if (isPositiveNumber(value))
|
|
130
|
+
return true;
|
|
131
|
+
if (!isPercentageString(value))
|
|
132
|
+
return false;
|
|
133
|
+
const percent = parseFloat(value.trim().slice(0, -1));
|
|
134
|
+
return Number.isFinite(percent) && percent > 0;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Check if a value is a positive integer.
|
|
138
|
+
*
|
|
139
|
+
* @param {*} value - Value to test
|
|
140
|
+
* @returns {boolean} True if the value is an integer greater than 0
|
|
141
|
+
*/
|
|
142
|
+
function isPositiveInt(value) {
|
|
143
|
+
return typeof value === 'number' && Number.isInteger(value) && value > 0;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Parse a percentage string to decimal form.
|
|
147
|
+
* Extracts numeric value before '%' and divides by 100.
|
|
148
|
+
*
|
|
149
|
+
* @param {string} v - Percentage string (e.g., "50%")
|
|
150
|
+
* @returns {number|null} Decimal form (e.g., 0.5) or null if invalid
|
|
151
|
+
*/
|
|
152
|
+
function parsePercentageString(v) {
|
|
153
|
+
if (!isPercentageString(v))
|
|
154
|
+
return null;
|
|
155
|
+
const num = parseFloat(v.trim().slice(0, -1));
|
|
156
|
+
return Number.isNaN(num) ? null : num / 100.0;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Convert a value (number, percentage string, or numeric string) to its
|
|
160
|
+
* decimal form. Unlike parsePercentageString which only handles '%' strings,
|
|
161
|
+
* this also accepts bare numbers and numeric strings.
|
|
162
|
+
* @param {*} value - Number (100 = 100), "100%" (= 1.0), or "100" (= 100)
|
|
163
|
+
* @returns {number} Decimal value, 0 if unparseable
|
|
164
|
+
*/
|
|
165
|
+
function toDecimal(value) {
|
|
166
|
+
if (typeof value === 'number')
|
|
167
|
+
return value;
|
|
168
|
+
if (typeof value === 'string') {
|
|
169
|
+
const trimmed = value.trim();
|
|
170
|
+
if (trimmed.endsWith('%')) {
|
|
171
|
+
const n = parseFloat(trimmed);
|
|
172
|
+
return Number.isNaN(n) ? 0 : n / 100;
|
|
173
|
+
}
|
|
174
|
+
const n = parseFloat(trimmed);
|
|
175
|
+
return Number.isNaN(n) ? 0 : n;
|
|
176
|
+
}
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Resolve a relative price expression (multiplier format) to absolute price.
|
|
181
|
+
* Supports expressions like "3x" to mean 3 times the reference price.
|
|
182
|
+
*
|
|
183
|
+
* @param {*} value - Value to resolve (e.g., "3x" or "0.5x")
|
|
184
|
+
* @param {number} startPrice - Reference price for multiplier calculation
|
|
185
|
+
* @param {string} [mode='min'] - "min" divides (price/multiplier), "max" multiplies (price*multiplier)
|
|
186
|
+
* @returns {number|null} Resolved price or null if value is not a relative expression
|
|
187
|
+
*/
|
|
188
|
+
function resolveRelativePrice(value, startPrice, mode = 'min') {
|
|
189
|
+
if (typeof value === 'string') {
|
|
190
|
+
if (/^[\s]*[0-9]+(?:\.[0-9]+)?x[\s]*$/i.test(value)) {
|
|
191
|
+
const multiplier = parseFloat(value.trim().toLowerCase().slice(0, -1));
|
|
192
|
+
if (!Number.isNaN(multiplier) && Number.isFinite(startPrice) && multiplier !== 0) {
|
|
193
|
+
return mode === 'min' ? startPrice / multiplier : startPrice * multiplier;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
// ================================================================================
|
|
200
|
+
// SECTION 2: FUND CALCULATIONS
|
|
201
|
+
// ================================================================================
|
|
202
|
+
/**
|
|
203
|
+
* Calculate chain fund totals from account balances and committed orders.
|
|
204
|
+
* Reconciles free/locked balances with committed capital to produce fund summary.
|
|
205
|
+
*
|
|
206
|
+
* @param {Object} accountTotals - Account balance snapshot with buyFree, sellFree, buy, sell properties
|
|
207
|
+
* @param {Object} committedChain - Committed capital with buy and sell properties
|
|
208
|
+
* @returns {Object} Summary object with chainFreeBuy, chainFreeSell, committedChainBuy,
|
|
209
|
+
* committedChainSell, freePlusLockedBuy, freePlusLockedSell, chainTotalBuy, chainTotalSell
|
|
210
|
+
*/
|
|
211
|
+
function computeChainFundTotals(accountTotals, committedChain) {
|
|
212
|
+
const chainFreeBuy = toFiniteNumber(accountTotals?.buyFree);
|
|
213
|
+
const chainFreeSell = toFiniteNumber(accountTotals?.sellFree);
|
|
214
|
+
const committedChainBuy = toFiniteNumber(committedChain?.buy);
|
|
215
|
+
const committedChainSell = toFiniteNumber(committedChain?.sell);
|
|
216
|
+
const freePlusLockedBuy = chainFreeBuy + committedChainBuy;
|
|
217
|
+
const freePlusLockedSell = chainFreeSell + committedChainSell;
|
|
218
|
+
const chainTotalBuy = isValidNumber(accountTotals?.buy)
|
|
219
|
+
? Math.max(Number(accountTotals.buy), freePlusLockedBuy)
|
|
220
|
+
: freePlusLockedBuy;
|
|
221
|
+
const chainTotalSell = isValidNumber(accountTotals?.sell)
|
|
222
|
+
? Math.max(Number(accountTotals.sell), freePlusLockedSell)
|
|
223
|
+
: freePlusLockedSell;
|
|
224
|
+
return {
|
|
225
|
+
chainFreeBuy,
|
|
226
|
+
chainFreeSell,
|
|
227
|
+
committedChainBuy,
|
|
228
|
+
committedChainSell,
|
|
229
|
+
freePlusLockedBuy,
|
|
230
|
+
freePlusLockedSell,
|
|
231
|
+
chainTotalBuy,
|
|
232
|
+
chainTotalSell
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
// ================================================================================
|
|
236
|
+
// SECTION 2A: PRECISION QUANTIZATION
|
|
237
|
+
// ================================================================================
|
|
238
|
+
/**
|
|
239
|
+
* Quantize a float value by round-tripping through blockchain integer representation.
|
|
240
|
+
* Converts float → blockchain int (satoshi-level precision) → float.
|
|
241
|
+
* Eliminates floating-point accumulation errors.
|
|
242
|
+
*
|
|
243
|
+
* @param {number} value - Float value to quantize
|
|
244
|
+
* @param {number} precision - Asset precision (satoshis)
|
|
245
|
+
* @returns {number} Quantized float value
|
|
246
|
+
*/
|
|
247
|
+
function quantizeFloat(value, precision) {
|
|
248
|
+
return blockchainToFloat(floatToBlockchainInt(value, precision), precision);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Normalize an integer value by round-tripping through float representation.
|
|
252
|
+
* Converts int → float (readable format) → blockchain int.
|
|
253
|
+
* Ensures the integer aligns with precision boundaries.
|
|
254
|
+
* Used for precision-aware comparisons.
|
|
255
|
+
*
|
|
256
|
+
* @param {number} value - Integer value to normalize
|
|
257
|
+
* @param {number} precision - Asset precision (satoshis)
|
|
258
|
+
* @returns {number} Normalized integer value
|
|
259
|
+
*/
|
|
260
|
+
function normalizeInt(value, precision) {
|
|
261
|
+
return floatToBlockchainInt(blockchainToFloat(value, precision), precision);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Fee cache local to math.js for getAssetFees.
|
|
265
|
+
* Will be populated by system.js::initializeFeeCache.
|
|
266
|
+
*/
|
|
267
|
+
let feeCache = {};
|
|
268
|
+
/**
|
|
269
|
+
* @private Set the fee cache (called by system.js::initializeFeeCache).
|
|
270
|
+
*
|
|
271
|
+
* @param {Object} cache - Fee cache object keyed by asset symbol
|
|
272
|
+
* @returns {void}
|
|
273
|
+
*/
|
|
274
|
+
function _setFeeCache(cache) { feeCache = cache; }
|
|
275
|
+
/**
|
|
276
|
+
* Get fee information for an asset.
|
|
277
|
+
|
|
278
|
+
* Returns fee structure or net proceeds calculation if asset amount provided.
|
|
279
|
+
*
|
|
280
|
+
* @param {string} assetSymbol - Asset symbol (e.g., "BTS", "USD")
|
|
281
|
+
* @param {number} [assetAmount=null] - Asset amount to calculate net proceeds
|
|
282
|
+
* @param {boolean} [isMaker=true] - Whether this is a maker or taker (affects BTS fees)
|
|
283
|
+
* @returns {Object} Fee structure with create/update/net fees or net proceeds if amount provided
|
|
284
|
+
* @throws {Error} If fees not cached (call initializeFeeCache first)
|
|
285
|
+
*/
|
|
286
|
+
function getAssetFees(assetSymbol, assetAmount = null, isMaker = true) {
|
|
287
|
+
const cachedFees = feeCache[assetSymbol];
|
|
288
|
+
if (!cachedFees) {
|
|
289
|
+
throw new Error(`Fees not cached for ${assetSymbol}. Call initializeFeeCache first.`);
|
|
290
|
+
}
|
|
291
|
+
if (assetSymbol === 'BTS') {
|
|
292
|
+
const orderCreationFee = cachedFees.limitOrderCreate.bts;
|
|
293
|
+
const orderUpdateFee = cachedFees.limitOrderUpdate.bts;
|
|
294
|
+
const orderCancelFee = cachedFees.limitOrderCancel?.bts || 0;
|
|
295
|
+
const makerFeeDiscountPercent = Number.isFinite(Number(cachedFees.makerFeeDiscountPercent))
|
|
296
|
+
? Math.max(0, Number(cachedFees.makerFeeDiscountPercent))
|
|
297
|
+
: FEE_PARAMETERS.MAKER_REFUND_PERCENT;
|
|
298
|
+
const makerNetFee = orderCreationFee * FEE_PARAMETERS.MAKER_FEE_PERCENT;
|
|
299
|
+
const takerNetFee = orderCreationFee * FEE_PARAMETERS.TAKER_FEE_PERCENT;
|
|
300
|
+
const netFee = isMaker ? makerNetFee : takerNetFee;
|
|
301
|
+
if (assetAmount !== null && assetAmount !== undefined) {
|
|
302
|
+
const amount = Number(assetAmount);
|
|
303
|
+
const refund = isMaker ? (orderCreationFee * makerFeeDiscountPercent) : 0;
|
|
304
|
+
const netProceeds = amount + refund;
|
|
305
|
+
return {
|
|
306
|
+
netProceeds: netProceeds,
|
|
307
|
+
total: netProceeds,
|
|
308
|
+
refund: refund,
|
|
309
|
+
isMaker: isMaker
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
total: netFee + orderUpdateFee,
|
|
314
|
+
createFee: orderCreationFee,
|
|
315
|
+
updateFee: orderUpdateFee,
|
|
316
|
+
cancelFee: orderCancelFee,
|
|
317
|
+
makerFeeDiscountPercent,
|
|
318
|
+
makerNetFee: makerNetFee,
|
|
319
|
+
takerNetFee: takerNetFee,
|
|
320
|
+
netFee: netFee,
|
|
321
|
+
isMaker: isMaker
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
const chargesMarketFees = cachedFees.chargesMarketFees === true;
|
|
325
|
+
const feePercent = chargesMarketFees && isMaker
|
|
326
|
+
? (cachedFees.marketFee?.percent || 0)
|
|
327
|
+
: chargesMarketFees
|
|
328
|
+
? (cachedFees.takerFee?.percent || cachedFees.marketFee?.percent || 0)
|
|
329
|
+
: 0;
|
|
330
|
+
if (assetAmount !== null && assetAmount !== undefined) {
|
|
331
|
+
const amount = Number(assetAmount);
|
|
332
|
+
const maxMarketFee = Number.isFinite(Number(cachedFees.maxMarketFee?.float))
|
|
333
|
+
? Math.max(0, Number(cachedFees.maxMarketFee.float))
|
|
334
|
+
: Infinity;
|
|
335
|
+
const feeAmount = Math.min((amount * feePercent) / 100, maxMarketFee);
|
|
336
|
+
const netProceeds = amount - feeAmount;
|
|
337
|
+
return {
|
|
338
|
+
netProceeds: netProceeds,
|
|
339
|
+
total: netProceeds,
|
|
340
|
+
feeAmount: feeAmount,
|
|
341
|
+
feePercent: feePercent,
|
|
342
|
+
isMaker: isMaker
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
return {
|
|
346
|
+
marketFee: cachedFees.marketFee?.percent || 0,
|
|
347
|
+
takerFee: cachedFees.takerFee?.percent || 0,
|
|
348
|
+
percent: feePercent
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Calculate available funds for a specific side (buy or sell).
|
|
353
|
+
* Deducts virtual reservations, BTS fees owed, and BTS fee reservation from chain-free balance.
|
|
354
|
+
*
|
|
355
|
+
* @param {string} side - Trading side: "buy" or "sell"
|
|
356
|
+
* @param {Object} accountTotals - Account balance snapshot
|
|
357
|
+
* @param {Object} funds - Fund allocation object with virtual, btsFeesOwed properties
|
|
358
|
+
* @param {string} assetA - First asset symbol
|
|
359
|
+
* @param {string} assetB - Second asset symbol
|
|
360
|
+
* @param {Object} [activeOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
|
|
361
|
+
* @returns {number} Available funds for the side (0 if side invalid or insufficient funds)
|
|
362
|
+
*/
|
|
363
|
+
function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB, activeOrders = null, configMinBtsValue = null, feeParams = null) {
|
|
364
|
+
if (side !== 'buy' && side !== 'sell')
|
|
365
|
+
return 0;
|
|
366
|
+
const chainFree = toFiniteNumber(side === 'buy' ? accountTotals?.buyFree : accountTotals?.sellFree);
|
|
367
|
+
const virtualReservation = toFiniteNumber(side === 'buy' ? funds.virtual?.buy : funds.virtual?.sell);
|
|
368
|
+
const btsFeesOwed = toFiniteNumber(funds.btsFeesOwed);
|
|
369
|
+
const btsSide = (assetA === 'BTS') ? 'sell' : (assetB === 'BTS') ? 'buy' : null;
|
|
370
|
+
const btsReservationMultiplier = feeParams?.BTS_RESERVATION_MULTIPLIER ?? FEE_PARAMETERS.BTS_RESERVATION_MULTIPLIER;
|
|
371
|
+
let btsFeesReservation = 0;
|
|
372
|
+
if (btsSide === side && activeOrders) {
|
|
373
|
+
const targetBuy = Math.max(0, toFiniteNumber(activeOrders?.buy, 1));
|
|
374
|
+
const targetSell = Math.max(0, toFiniteNumber(activeOrders?.sell, 1));
|
|
375
|
+
const totalTargetOrders = targetBuy + targetSell;
|
|
376
|
+
btsFeesReservation = calculateOrderCreationFees(assetA, assetB, totalTargetOrders, btsReservationMultiplier);
|
|
377
|
+
}
|
|
378
|
+
const currentFeesOwed = (btsSide === side) ? btsFeesOwed : 0;
|
|
379
|
+
// Non-BTS pair: reserve proportional share for BTS fee budget
|
|
380
|
+
if (!btsSide && activeOrders && funds?.btsBalance != null) {
|
|
381
|
+
const targetBuy = Math.max(0, toFiniteNumber(activeOrders?.buy, 1));
|
|
382
|
+
const targetSell = Math.max(0, toFiniteNumber(activeOrders?.sell, 1));
|
|
383
|
+
const totalTargetOrders = targetBuy + targetSell;
|
|
384
|
+
const formulaBudget = calculateOrderCreationFees(assetA, assetB, totalTargetOrders, btsReservationMultiplier);
|
|
385
|
+
const effectiveMin = (configMinBtsValue > 0) ? configMinBtsValue : formulaBudget;
|
|
386
|
+
const btsFree = toFiniteNumber(funds?.btsBalance?.free, 0);
|
|
387
|
+
const btsDeficit = Math.max(0, effectiveMin - btsFree);
|
|
388
|
+
if (btsDeficit > 0) {
|
|
389
|
+
const totalFree = toFiniteNumber(accountTotals?.buyFree, 0)
|
|
390
|
+
+ toFiniteNumber(accountTotals?.sellFree, 0);
|
|
391
|
+
if (totalFree > 0) {
|
|
392
|
+
const sideFree = toFiniteNumber(side === 'buy' ? accountTotals?.buyFree : accountTotals?.sellFree, 0);
|
|
393
|
+
const share = sideFree / totalFree;
|
|
394
|
+
return Math.max(0, chainFree - virtualReservation - btsDeficit * share);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return Math.max(0, chainFree - virtualReservation - currentFeesOwed - btsFeesReservation);
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Find the best (highest) buy price and best (lowest) sell price from active orders.
|
|
402
|
+
*
|
|
403
|
+
* @param {Array<Object>} activeBuys - Active buy orders with price property
|
|
404
|
+
* @param {Array<Object>} activeSells - Active sell orders with price property
|
|
405
|
+
* @returns {{bestBuy: number|null, bestSell: number|null}} Best prices or null if no orders
|
|
406
|
+
*/
|
|
407
|
+
function getGridBestPrices(activeBuys, activeSells) {
|
|
408
|
+
const bestBuy = activeBuys.length > 0 ? Math.max(...activeBuys.map(o => o.price)) : null;
|
|
409
|
+
const bestSell = activeSells.length > 0 ? Math.min(...activeSells.map(o => o.price)) : null;
|
|
410
|
+
return { bestBuy, bestSell };
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Calculate bid-ask spread percentage from active buy and sell orders.
|
|
414
|
+
* Spread = (bestSell / bestBuy - 1) * 100 (percentage).
|
|
415
|
+
*
|
|
416
|
+
* @param {Array<Object>} activeBuys - Active buy orders with price property
|
|
417
|
+
* @param {Array<Object>} activeSells - Active sell orders with price property
|
|
418
|
+
* @returns {number} Spread percentage or 0 if insufficient data
|
|
419
|
+
*/
|
|
420
|
+
function calculateSpreadFromOrders(activeBuys, activeSells) {
|
|
421
|
+
const { bestBuy, bestSell } = getGridBestPrices(activeBuys, activeSells);
|
|
422
|
+
if (bestBuy === null || bestSell === null || bestBuy === 0)
|
|
423
|
+
return 0;
|
|
424
|
+
return ((bestSell / bestBuy) - 1) * 100;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Resolve a config value to a numeric amount.
|
|
428
|
+
* Interprets percentage strings, numeric strings, or direct numbers.
|
|
429
|
+
*
|
|
430
|
+
* @param {*} value - Value to resolve (string, number, or percentage)
|
|
431
|
+
* @param {number} total - Total amount for percentage calculations
|
|
432
|
+
* @returns {number} Resolved numeric value or 0 if uninterpretable
|
|
433
|
+
*/
|
|
434
|
+
function resolveConfigValue(value, total) {
|
|
435
|
+
if (typeof value === 'number')
|
|
436
|
+
return value;
|
|
437
|
+
if (typeof value === 'string') {
|
|
438
|
+
const p = parsePercentageString(value);
|
|
439
|
+
if (p !== null) {
|
|
440
|
+
if (total === null || total === undefined)
|
|
441
|
+
return 0;
|
|
442
|
+
return total * p;
|
|
443
|
+
}
|
|
444
|
+
const n = parseFloat(value);
|
|
445
|
+
return Number.isNaN(n) ? 0 : n;
|
|
446
|
+
}
|
|
447
|
+
return 0;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Resolve a config value to a numeric amount, accounting for shared-account
|
|
451
|
+
* fund registry. If the bot has a registry entry, returns the proportional
|
|
452
|
+
* share of chainTotal. Falls back to standard resolveConfigValue if the
|
|
453
|
+
* registry has no entry for this bot (single-bot accounts or unregistered).
|
|
454
|
+
*
|
|
455
|
+
* @param {*} value - Value to resolve (string, number, or percentage)
|
|
456
|
+
* @param {number} chainTotal - Total chain balance for this side
|
|
457
|
+
* @param {string} account - Blockchain account name
|
|
458
|
+
* @param {string} botName - Bot identifier
|
|
459
|
+
* @param {'buy'|'sell'} side - Trade side
|
|
460
|
+
* @returns {number} Resolved numeric value or 0 if uninterpretable
|
|
461
|
+
*/
|
|
462
|
+
function resolveConfigValueWithRegistry(value, chainTotal, account, botName, side) {
|
|
463
|
+
const effective = fundRegistry.getEffectiveAllocationSync(account, botName, side, chainTotal);
|
|
464
|
+
if (effective !== null)
|
|
465
|
+
return effective;
|
|
466
|
+
return resolveConfigValue(value, chainTotal);
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Check if account totals contain valid buy/sell balance data.
|
|
470
|
+
*
|
|
471
|
+
* @param {Object} accountTotals - Account total balances object
|
|
472
|
+
* @param {boolean} [checkFree=true] - Check free balances if true, else check total balances
|
|
473
|
+
* @returns {boolean} True if both buy and sell values are valid finite numbers
|
|
474
|
+
*/
|
|
475
|
+
function hasValidAccountTotals(accountTotals, checkFree = true) {
|
|
476
|
+
if (!accountTotals)
|
|
477
|
+
return false;
|
|
478
|
+
const buyKey = checkFree ? 'buyFree' : 'buy';
|
|
479
|
+
const sellKey = checkFree ? 'sellFree' : 'sell';
|
|
480
|
+
return isValidNumber(accountTotals[buyKey]) && isValidNumber(accountTotals[sellKey]);
|
|
481
|
+
}
|
|
482
|
+
// ================================================================================
|
|
483
|
+
// SECTION 3: BLOCKCHAIN CONVERSIONS & PRECISION
|
|
484
|
+
// ================================================================================
|
|
485
|
+
/**
|
|
486
|
+
* Convert blockchain integer to float using asset precision.
|
|
487
|
+
* Divides by 10^precision to convert satoshi-level units to human-readable float.
|
|
488
|
+
* Formula: float = blockchain_int / (10^precision)
|
|
489
|
+
*
|
|
490
|
+
* @param {number} intValue - Integer value from blockchain (satoshi units)
|
|
491
|
+
* @param {number} precision - Asset precision level (exponent: 5, 8, 4, etc)
|
|
492
|
+
* @returns {number} Float representation in human-readable units
|
|
493
|
+
* @throws {Error} If precision is invalid
|
|
494
|
+
*/
|
|
495
|
+
function blockchainToFloat(intValue, precision) {
|
|
496
|
+
if (!isValidNumber(precision)) {
|
|
497
|
+
throw new Error(`Invalid precision for blockchainToFloat: ${precision}`);
|
|
498
|
+
}
|
|
499
|
+
return toFiniteNumber(intValue) / Math.pow(10, Number(precision));
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Convert float to blockchain integer using asset precision.
|
|
503
|
+
* Multiplies by 10^precision and rounds to satoshi-level units.
|
|
504
|
+
* Clamps to MAX_INT64/MIN_INT64 to prevent overflow.
|
|
505
|
+
* Formula: blockchain_int = round(float * (10^precision))
|
|
506
|
+
*
|
|
507
|
+
* Round-trip (float → int → float) eliminates floating-point accumulation errors.
|
|
508
|
+
* Overflow protection: Blockchain integers must fit in signed 64-bit range.
|
|
509
|
+
*
|
|
510
|
+
* @param {number} floatValue - Float value to convert (human-readable units)
|
|
511
|
+
* @param {number} precision - Asset precision level (exponent: 5, 8, 4, etc)
|
|
512
|
+
* @returns {number} Blockchain integer representation (satoshi units)
|
|
513
|
+
* @throws {Error} If precision is invalid
|
|
514
|
+
*/
|
|
515
|
+
function floatToBlockchainInt(floatValue, precision) {
|
|
516
|
+
if (!isValidNumber(precision)) {
|
|
517
|
+
throw new Error(`Invalid precision for floatToBlockchainInt: ${precision}`);
|
|
518
|
+
}
|
|
519
|
+
const p = Number(precision);
|
|
520
|
+
const v = toFiniteNumber(floatValue);
|
|
521
|
+
const scaled = Math.round(v * Math.pow(10, p));
|
|
522
|
+
if (scaled > MAX_INT64 || scaled < MIN_INT64) {
|
|
523
|
+
mathLogger.warn(`Overflow detected: ${floatValue} with precision ${p} resulted in ${scaled}. Clamping to safe limits.`);
|
|
524
|
+
return scaled > 0 ? MAX_INT64 : MIN_INT64;
|
|
525
|
+
}
|
|
526
|
+
return scaled;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Get asset precision for a specific order type (BUY or SELL).
|
|
530
|
+
* BUY orders size in assetB, SELL orders size in assetA.
|
|
531
|
+
*
|
|
532
|
+
* @param {Object} assets - Asset metadata with assetA and assetB
|
|
533
|
+
* @param {string} orderType - Order type (ORDER_TYPES.BUY or ORDER_TYPES.SELL)
|
|
534
|
+
* @returns {number} Asset precision
|
|
535
|
+
* @throws {Error} If precision missing for the required asset
|
|
536
|
+
*/
|
|
537
|
+
function getPrecisionByOrderType(assets, orderType) {
|
|
538
|
+
const asset = orderType === ORDER_TYPES.SELL ? assets?.assetA : assets?.assetB;
|
|
539
|
+
const side = orderType === ORDER_TYPES.SELL ? 'SELL' : 'BUY';
|
|
540
|
+
if (typeof asset?.precision !== 'number') {
|
|
541
|
+
const errorMsg = `CRITICAL: Asset precision missing for ${side} orders. Asset: ${asset?.symbol || '(unknown)'}. Cannot determine blockchain precision.`;
|
|
542
|
+
mathLogger.error(`${errorMsg}`);
|
|
543
|
+
throw new Error(errorMsg);
|
|
544
|
+
}
|
|
545
|
+
return asset.precision;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Get asset precision for a specific trading side.
|
|
549
|
+
*
|
|
550
|
+
* @param {Object} assets - Asset metadata with assetA and assetB
|
|
551
|
+
* @param {string} side - Side ("buy" or "sell")
|
|
552
|
+
* @returns {number} Asset precision for the side
|
|
553
|
+
* @throws {Error} If precision missing
|
|
554
|
+
*/
|
|
555
|
+
function getPrecisionForSide(assets, side) {
|
|
556
|
+
const asset = side === 'buy' ? assets?.assetB : assets?.assetA;
|
|
557
|
+
const sideUpper = side === 'buy' ? 'BUY' : 'SELL';
|
|
558
|
+
if (typeof asset?.precision !== 'number') {
|
|
559
|
+
const errorMsg = `CRITICAL: Asset precision missing for ${sideUpper} side. Asset: ${asset?.symbol || '(unknown)'}. Cannot determine blockchain precision.`;
|
|
560
|
+
mathLogger.error(`${errorMsg}`);
|
|
561
|
+
throw new Error(errorMsg);
|
|
562
|
+
}
|
|
563
|
+
return asset.precision;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Get asset precisions for both assetA and assetB.
|
|
567
|
+
*
|
|
568
|
+
* @param {Object} assets - Asset metadata with assetA and assetB
|
|
569
|
+
* @returns {Object} Object with A and B precision properties
|
|
570
|
+
* @throws {Error} If precision missing for either asset
|
|
571
|
+
*/
|
|
572
|
+
function getPrecisionsForManager(assets) {
|
|
573
|
+
if (typeof assets?.assetA?.precision !== 'number') {
|
|
574
|
+
const errorMsg = `CRITICAL: Asset precision missing for assetA (${assets?.assetA?.symbol || '(unknown)'}). Cannot determine blockchain precision.`;
|
|
575
|
+
mathLogger.error(`${errorMsg}`);
|
|
576
|
+
throw new Error(errorMsg);
|
|
577
|
+
}
|
|
578
|
+
if (typeof assets?.assetB?.precision !== 'number') {
|
|
579
|
+
const errorMsg = `CRITICAL: Asset precision missing for assetB (${assets?.assetB?.symbol || '(unknown)'}). Cannot determine blockchain precision.`;
|
|
580
|
+
mathLogger.error(`${errorMsg}`);
|
|
581
|
+
throw new Error(errorMsg);
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
A: assets.assetA.precision,
|
|
585
|
+
B: assets.assetB.precision
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Calculate precision slack (rounding tolerance) for a given precision level.
|
|
590
|
+
* Used for safe comparison of blockchain values that may differ by rounding.
|
|
591
|
+
*
|
|
592
|
+
* @param {number} precision - Asset precision level
|
|
593
|
+
* @param {number} [factor=2] - Multiplier for slack (default 2)
|
|
594
|
+
* @returns {number} Tolerance value (e.g., 2 * 10^-8 for 8-decimal precision)
|
|
595
|
+
*/
|
|
596
|
+
function getPrecisionSlack(precision, factor = 2) {
|
|
597
|
+
return factor * Math.pow(10, -precision);
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Unified precision lookup for assets.
|
|
601
|
+
*
|
|
602
|
+
* @param {Object} assets - Assets object with assetA and assetB
|
|
603
|
+
* @param {Object} [options={}] - Lookup options { type, side, proceeds }
|
|
604
|
+
* @returns {number} Asset precision
|
|
605
|
+
*/
|
|
606
|
+
function getPrecision(assets, { type, side, proceeds = false } = {}) {
|
|
607
|
+
if (!assets)
|
|
608
|
+
throw new Error("Assets object required for precision lookup");
|
|
609
|
+
// Determine target side: side param priority, then type param
|
|
610
|
+
let isSellSide;
|
|
611
|
+
if (side)
|
|
612
|
+
isSellSide = (side === 'sell');
|
|
613
|
+
else if (type)
|
|
614
|
+
isSellSide = (type === ORDER_TYPES.SELL);
|
|
615
|
+
else
|
|
616
|
+
throw new Error("Either 'type' or 'side' must be provided for getPrecision");
|
|
617
|
+
// Proceeds logic: SELL (assetA) results in assetB proceeds; BUY (assetB) results in assetA
|
|
618
|
+
const targetIsAssetA = proceeds ? !isSellSide : isSellSide;
|
|
619
|
+
const asset = targetIsAssetA ? assets.assetA : assets.assetB;
|
|
620
|
+
if (typeof asset?.precision !== 'number') {
|
|
621
|
+
const label = targetIsAssetA ? 'assetA' : 'assetB';
|
|
622
|
+
throw new Error(`CRITICAL: Precision missing for ${label} (${asset?.symbol || 'unknown'}).`);
|
|
623
|
+
}
|
|
624
|
+
return asset.precision;
|
|
625
|
+
}
|
|
626
|
+
// ================================================================================
|
|
627
|
+
// SECTION 4: PRICE OPERATIONS (PART 1 - Tolerance)
|
|
628
|
+
// ================================================================================
|
|
629
|
+
/**
|
|
630
|
+
* Calculate price tolerance for order matching on-chain.
|
|
631
|
+
* Accounts for precision limits of both assets to determine acceptable price deviation.
|
|
632
|
+
* Used when matching grid orders to blockchain orders.
|
|
633
|
+
*
|
|
634
|
+
* NOTE on the orderSize parameter: larger sizes produce tighter (more precise)
|
|
635
|
+
* tolerance values. When using this function for duplicate-price-level
|
|
636
|
+
* detection, always pass Math.max(sizeA, sizeB) as orderSize — a tiny dust
|
|
637
|
+
* order would inflate the tolerance window and falsely match distant prices.
|
|
638
|
+
*
|
|
639
|
+
* @param {number} gridPrice - Grid order price
|
|
640
|
+
* @param {number} orderSize - Order size on primary side (larger = tighter tolerance)
|
|
641
|
+
* @param {string} orderType - Order type ("buy" or "sell")
|
|
642
|
+
* @param {Object} [assets=null] - Asset metadata with precision (required)
|
|
643
|
+
* @returns {number|null} Price tolerance value or null if invalid inputs
|
|
644
|
+
* @throws {Error} If assets missing or precisions invalid
|
|
645
|
+
*/
|
|
646
|
+
function calculatePriceTolerance(gridPrice, orderSize, orderType, assets = null) {
|
|
647
|
+
if (!isValidNumber(gridPrice) || !isValidNumber(orderSize))
|
|
648
|
+
return null;
|
|
649
|
+
if (!assets)
|
|
650
|
+
throw new Error("CRITICAL: Assets object required for calculatePriceTolerance");
|
|
651
|
+
const precisionA = assets.assetA?.precision;
|
|
652
|
+
const precisionB = assets.assetB?.precision;
|
|
653
|
+
if (typeof precisionA !== 'number' || typeof precisionB !== 'number') {
|
|
654
|
+
throw new Error(`CRITICAL: Missing precision for price tolerance (A=${precisionA}, B=${precisionB})`);
|
|
655
|
+
}
|
|
656
|
+
if (!orderSize || orderSize <= 0)
|
|
657
|
+
return null;
|
|
658
|
+
// Minimum amount in blockchain satoshis that the chain will accept for an order.
|
|
659
|
+
// Uses GRID_LIMITS.MIN_ORDER_SIZE_FACTOR (same constant as getMinOrderSize).
|
|
660
|
+
let orderSizeA, orderSizeB;
|
|
661
|
+
if (orderType === 'sell' || orderType === 'SELL' || orderType === 'Sell') {
|
|
662
|
+
orderSizeA = orderSize;
|
|
663
|
+
orderSizeB = orderSize * gridPrice;
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
orderSizeB = orderSize;
|
|
667
|
+
orderSizeA = orderSize / gridPrice;
|
|
668
|
+
}
|
|
669
|
+
const minOrderSats = GRID_LIMITS.MIN_ORDER_SIZE_FACTOR;
|
|
670
|
+
const satsA = Math.max(orderSizeA * Math.pow(10, precisionA), minOrderSats);
|
|
671
|
+
const satsB = Math.max(orderSizeB * Math.pow(10, precisionB), minOrderSats);
|
|
672
|
+
const termA = 1 / satsA;
|
|
673
|
+
const termB = 1 / satsB;
|
|
674
|
+
const tolerance = (termA + termB) * gridPrice;
|
|
675
|
+
const maxTolerance = Math.max(gridPrice * GRID_LIMITS.PRICE_TOLERANCE_MAX_PERCENT, GRID_LIMITS.PRICE_TOLERANCE_MIN_ABSOLUTE);
|
|
676
|
+
return Math.min(tolerance, maxTolerance);
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Validate order amounts are within blockchain limits (0 < INT64_MAX).
|
|
680
|
+
* Converts floats to blockchain integers and checks they fit in signed 64-bit integers.
|
|
681
|
+
*
|
|
682
|
+
* @param {number} amountToSell - Amount to sell (float)
|
|
683
|
+
* @param {number} minToReceive - Minimum amount to receive (float)
|
|
684
|
+
* @param {number} sellPrecision - Precision of sell asset
|
|
685
|
+
* @param {number} receivePrecision - Precision of receive asset
|
|
686
|
+
* @returns {boolean} True if both amounts are valid and within limits
|
|
687
|
+
*/
|
|
688
|
+
function validateOrderAmountsWithinLimits(amountToSell, minToReceive, sellPrecision, receivePrecision) {
|
|
689
|
+
const sellPrecFloat = Math.pow(10, toFiniteNumber(sellPrecision));
|
|
690
|
+
const receivePrecFloat = Math.pow(10, toFiniteNumber(receivePrecision));
|
|
691
|
+
const sellInt = Math.round(toFiniteNumber(amountToSell) * sellPrecFloat);
|
|
692
|
+
const receiveInt = Math.round(toFiniteNumber(minToReceive) * receivePrecFloat);
|
|
693
|
+
const withinLimits = sellInt <= MAX_INT64 && receiveInt <= MAX_INT64 && sellInt > 0 && receiveInt > 0;
|
|
694
|
+
if (!withinLimits) {
|
|
695
|
+
mathLogger.warn(`Order amounts exceed safe limits or are invalid. Sell: ${amountToSell} = ${sellInt}, Receive: ${minToReceive} = ${receiveInt}. Max allowed: ${MAX_INT64}`);
|
|
696
|
+
}
|
|
697
|
+
return withinLimits;
|
|
698
|
+
}
|
|
699
|
+
// ================================================================================
|
|
700
|
+
// SECTION 5: DUST THRESHOLD & SIZE VALIDATION
|
|
701
|
+
// ================================================================================
|
|
702
|
+
/**
|
|
703
|
+
* Calculate minimum absolute order size for an order type.
|
|
704
|
+
* Returns factor * 10^-precision (e.g., 50 * 10^-8 for 8-decimal asset).
|
|
705
|
+
*
|
|
706
|
+
* @param {string} orderType - Order type (BUY or SELL)
|
|
707
|
+
* @param {Object} assets - Asset metadata with assetA and assetB precisions
|
|
708
|
+
* @param {number} [factor=50] - Minimum size factor (default 50)
|
|
709
|
+
* @returns {number} Minimum order size in asset units
|
|
710
|
+
* @throws {Error} If precision cannot be determined
|
|
711
|
+
*/
|
|
712
|
+
function getMinOrderSize(orderType, assets, factor = 50) {
|
|
713
|
+
const f = Number(factor);
|
|
714
|
+
if (!f || !Number.isFinite(f) || f <= 0)
|
|
715
|
+
return 0;
|
|
716
|
+
let precision = null;
|
|
717
|
+
if (assets) {
|
|
718
|
+
if ((orderType === ORDER_TYPES.SELL) && assets.assetA)
|
|
719
|
+
precision = assets.assetA.precision;
|
|
720
|
+
else if ((orderType === ORDER_TYPES.BUY) && assets.assetB)
|
|
721
|
+
precision = assets.assetB.precision;
|
|
722
|
+
}
|
|
723
|
+
if (typeof precision !== 'number') {
|
|
724
|
+
throw new Error(`CRITICAL: Cannot determine minimum order size for ${orderType} - missing precision`);
|
|
725
|
+
}
|
|
726
|
+
return Number(f) * Math.pow(10, -precision);
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Calculate dust threshold factor as decimal fraction.
|
|
730
|
+
*
|
|
731
|
+
* @param {number} [dustThresholdPercent=5] - Dust threshold percentage (default 5%)
|
|
732
|
+
* @returns {number} Dust factor (e.g., 0.05 for 5%)
|
|
733
|
+
*/
|
|
734
|
+
function getDustThresholdFactor(dustThresholdPercent = 5) {
|
|
735
|
+
return dustThresholdPercent / 100;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Calculate single dust threshold for an ideal order size.
|
|
739
|
+
* Returns idealSize * (dustThresholdPercent / 100).
|
|
740
|
+
*
|
|
741
|
+
* @param {number} idealSize - Ideal/reference order size
|
|
742
|
+
* @param {number} [dustThresholdPercent=5] - Threshold percentage (default 5%)
|
|
743
|
+
* @returns {number} Single dust threshold (0 if idealSize invalid)
|
|
744
|
+
*/
|
|
745
|
+
function getSingleDustThreshold(idealSize, dustThresholdPercent = 5) {
|
|
746
|
+
if (!idealSize || idealSize <= 0)
|
|
747
|
+
return 0;
|
|
748
|
+
return idealSize * getDustThresholdFactor(dustThresholdPercent);
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Calculate double dust threshold for an ideal order size.
|
|
752
|
+
* Returns idealSize * (dustThresholdPercent / 100) * 2.
|
|
753
|
+
* Used to filter very small orders that would be uneconomical.
|
|
754
|
+
*
|
|
755
|
+
* @param {number} idealSize - Ideal/reference order size
|
|
756
|
+
* @param {number} [dustThresholdPercent=5] - Threshold percentage (default 5%)
|
|
757
|
+
* @returns {number} Double dust threshold (0 if idealSize invalid)
|
|
758
|
+
*/
|
|
759
|
+
function getDoubleDustThreshold(idealSize, dustThresholdPercent = 5) {
|
|
760
|
+
if (!idealSize || idealSize <= 0)
|
|
761
|
+
return 0;
|
|
762
|
+
return idealSize * getDustThresholdFactor(dustThresholdPercent) * 2;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Calculate minimum absolute order size (wrapper for getMinOrderSize with default factor).
|
|
766
|
+
*
|
|
767
|
+
* @param {string} orderType - Order type (BUY or SELL)
|
|
768
|
+
* @param {Object} assets - Asset metadata
|
|
769
|
+
* @param {number} [minFactor=50] - Minimum size factor (default 50)
|
|
770
|
+
* @returns {number} Minimum order size in asset units
|
|
771
|
+
*/
|
|
772
|
+
function getMinAbsoluteOrderSize(orderType, assets, minFactor = 50) {
|
|
773
|
+
return getMinOrderSize(orderType, assets, minFactor);
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Validate an order size against minimum absolute and dust thresholds.
|
|
777
|
+
* Returns detailed validation result with reasons if invalid.
|
|
778
|
+
*
|
|
779
|
+
* @param {number} orderSize - Order size to validate
|
|
780
|
+
* @param {string} orderType - Order type (BUY or SELL)
|
|
781
|
+
* @param {Object} assets - Asset metadata with precisions
|
|
782
|
+
* @param {number} [minFactor=50] - Minimum size factor (default 50)
|
|
783
|
+
* @param {number} [idealSize=null] - Ideal size for dust calculations
|
|
784
|
+
* @param {number} [dustThresholdPercent=5] - Dust threshold percentage (default 5%)
|
|
785
|
+
* @returns {Object} Validation result {isValid, reason, minAbsoluteSize, minDustSize}
|
|
786
|
+
*/
|
|
787
|
+
function validateOrderSize(orderSize, orderType, assets, minFactor = 50, idealSize = null, dustThresholdPercent = 5) {
|
|
788
|
+
const orderSizeFloat = toFiniteNumber(orderSize);
|
|
789
|
+
const minAbsoluteSize = getMinAbsoluteOrderSize(orderType, assets, minFactor);
|
|
790
|
+
let precision = null;
|
|
791
|
+
if (assets) {
|
|
792
|
+
if ((orderType === ORDER_TYPES.SELL) && assets.assetA)
|
|
793
|
+
precision = assets.assetA.precision;
|
|
794
|
+
else if ((orderType === ORDER_TYPES.BUY) && assets.assetB)
|
|
795
|
+
precision = assets.assetB.precision;
|
|
796
|
+
}
|
|
797
|
+
const displayPrecision = precision;
|
|
798
|
+
if (orderSizeFloat < minAbsoluteSize) {
|
|
799
|
+
return { isValid: false, reason: `Order size (${Format.formatAmountByPrecision(orderSizeFloat, displayPrecision)}) below absolute minimum (${Format.formatAmountByPrecision(minAbsoluteSize, displayPrecision)})`, minAbsoluteSize, minDustSize: null };
|
|
800
|
+
}
|
|
801
|
+
if (idealSize !== null && idealSize !== undefined && idealSize > 0) {
|
|
802
|
+
const minDustSize = getDoubleDustThreshold(idealSize, dustThresholdPercent);
|
|
803
|
+
if (orderSizeFloat < minDustSize) {
|
|
804
|
+
return { isValid: false, reason: `Order size (${Format.formatAmountByPrecision(orderSizeFloat, displayPrecision)}) below double-dust threshold (${Format.formatAmountByPrecision(minDustSize, displayPrecision)})`, minAbsoluteSize, minDustSize };
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
if (typeof precision === 'number') {
|
|
808
|
+
if (floatToBlockchainInt(orderSizeFloat, precision) <= 0) {
|
|
809
|
+
return { isValid: false, reason: `Order size (${orderSizeFloat}) rounds to 0 on blockchain`, minAbsoluteSize, minDustSize: idealSize ? getDoubleDustThreshold(idealSize, dustThresholdPercent) : null };
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return { isValid: true, reason: null, minAbsoluteSize, minDustSize: idealSize ? getDoubleDustThreshold(idealSize, dustThresholdPercent) : null };
|
|
813
|
+
}
|
|
814
|
+
// ================================================================================
|
|
815
|
+
// SECTION 9: ORDER SIZING & ALLOCATION
|
|
816
|
+
// ================================================================================
|
|
817
|
+
/**
|
|
818
|
+
* Allocate total funds across n orders using exponential weight distribution.
|
|
819
|
+
* Optionally enforces precision quantization to match blockchain constraints.
|
|
820
|
+
* If precision provided, adjusts the largest order to compensate for rounding errors.
|
|
821
|
+
*
|
|
822
|
+
* @param {number} totalFunds - Total funds to allocate
|
|
823
|
+
* @param {number} n - Number of orders to create allocations for
|
|
824
|
+
* @param {number} weight - Weight factor (0-1) controlling distribution steepness
|
|
825
|
+
* @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
|
|
826
|
+
* @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
|
|
827
|
+
* @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
|
|
828
|
+
* @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
|
|
829
|
+
* @returns {Array<number>} Array of n allocation sizes
|
|
830
|
+
*/
|
|
831
|
+
function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false, minSize = 0, precision = null) {
|
|
832
|
+
if (n <= 0)
|
|
833
|
+
return [];
|
|
834
|
+
if (!Number.isFinite(totalFunds) || totalFunds <= 0)
|
|
835
|
+
return new Array(n).fill(0);
|
|
836
|
+
const base = 1 - incrementFactor;
|
|
837
|
+
const rawWeights = new Array(n);
|
|
838
|
+
for (let i = 0; i < n; i++) {
|
|
839
|
+
const idx = reverse ? (n - 1 - i) : i;
|
|
840
|
+
rawWeights[i] = Math.pow(base, idx * weight);
|
|
841
|
+
}
|
|
842
|
+
const sizes = new Array(n).fill(0);
|
|
843
|
+
const totalWeight = rawWeights.reduce((s, w) => s + w, 0) || 1;
|
|
844
|
+
if (precision !== null && precision !== undefined) {
|
|
845
|
+
const totalUnits = floatToBlockchainInt(totalFunds, precision);
|
|
846
|
+
let unitsSummary = 0;
|
|
847
|
+
const units = new Array(n);
|
|
848
|
+
for (let i = 0; i < n; i++) {
|
|
849
|
+
units[i] = Math.round((rawWeights[i] / totalWeight) * totalUnits);
|
|
850
|
+
unitsSummary += units[i];
|
|
851
|
+
}
|
|
852
|
+
const diff = totalUnits - unitsSummary;
|
|
853
|
+
if (diff !== 0 && n > 0) {
|
|
854
|
+
let largestIdx = 0;
|
|
855
|
+
for (let j = 1; j < n; j++)
|
|
856
|
+
if (units[j] > units[largestIdx])
|
|
857
|
+
largestIdx = j;
|
|
858
|
+
const adjusted = units[largestIdx] + diff;
|
|
859
|
+
if (adjusted < 0) {
|
|
860
|
+
mathLogger.warn(`allocateFundsByWeights: rounding diff ${diff} exceeds largest slot ${units[largestIdx]}; total allocation will be less than target ${totalUnits}`);
|
|
861
|
+
}
|
|
862
|
+
units[largestIdx] = Math.max(0, adjusted);
|
|
863
|
+
}
|
|
864
|
+
for (let i = 0; i < n; i++)
|
|
865
|
+
sizes[i] = blockchainToFloat(units[i], precision);
|
|
866
|
+
}
|
|
867
|
+
else {
|
|
868
|
+
for (let i = 0; i < n; i++)
|
|
869
|
+
sizes[i] = (rawWeights[i] / totalWeight) * totalFunds;
|
|
870
|
+
}
|
|
871
|
+
return sizes;
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Calculate order sizes for a list of orders using weighted fund allocation.
|
|
875
|
+
* Allocates buy and sell funds separately using weight distribution from config.
|
|
876
|
+
* Preserves order sequence while adding size property to each order.
|
|
877
|
+
*
|
|
878
|
+
* @param {Array<Object>} orders - Array of order objects with type property
|
|
879
|
+
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
880
|
+
* @param {number} sellFunds - Total funds available for SELL orders
|
|
881
|
+
* @param {number} buyFunds - Total funds available for BUY orders
|
|
882
|
+
* @param {number} [minSellSize=0] - Minimum size for sell allocations
|
|
883
|
+
* @param {number} [minBuySize=0] - Minimum size for buy allocations
|
|
884
|
+
* @param {number} [precisionA=null] - Precision for assetA (SELL asset)
|
|
885
|
+
* @param {number} [precisionB=null] - Precision for assetB (BUY asset)
|
|
886
|
+
* @returns {Array<Object>} Orders array with size property added to each
|
|
887
|
+
*/
|
|
888
|
+
function calculateOrderSizes(orders, config, sellFunds, buyFunds, minSellSize = 0, minBuySize = 0, precisionA = null, precisionB = null) {
|
|
889
|
+
const { incrementPercent, weightDistribution: { sell: sellWeight, buy: buyWeight } } = config;
|
|
890
|
+
const incrementFactor = incrementPercent / 100;
|
|
891
|
+
const sellOrders = orders.filter(o => o.type === ORDER_TYPES.SELL);
|
|
892
|
+
const buyOrders = orders.filter(o => o.type === ORDER_TYPES.BUY);
|
|
893
|
+
const sellSizes = allocateFundsByWeights(sellFunds, sellOrders.length, sellWeight, incrementFactor, false, minSellSize, precisionA);
|
|
894
|
+
const buySizes = allocateFundsByWeights(buyFunds, buyOrders.length, buyWeight, incrementFactor, true, minBuySize, precisionB);
|
|
895
|
+
const sellState = { sizes: sellSizes, index: 0 };
|
|
896
|
+
const buyState = { sizes: buySizes, index: 0 };
|
|
897
|
+
return orders.map(order => {
|
|
898
|
+
let size = 0;
|
|
899
|
+
if (order.type === ORDER_TYPES.SELL) {
|
|
900
|
+
if (sellState.index >= sellState.sizes.length)
|
|
901
|
+
throw new Error(`calculateOrderSizes: sell index ${sellState.index} out of bounds (len=${sellState.sizes.length})`);
|
|
902
|
+
size = sellState.sizes[sellState.index++];
|
|
903
|
+
}
|
|
904
|
+
else if (order.type === ORDER_TYPES.BUY) {
|
|
905
|
+
if (buyState.index >= buyState.sizes.length)
|
|
906
|
+
throw new Error(`calculateOrderSizes: buy index ${buyState.index} out of bounds (len=${buyState.sizes.length})`);
|
|
907
|
+
size = buyState.sizes[buyState.index++];
|
|
908
|
+
}
|
|
909
|
+
return { ...order, size };
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Calculate order sizes for rotation operations.
|
|
914
|
+
* Combines available funds with existing grid allocation for sizing.
|
|
915
|
+
* Used during order refreshes when rotating orders to new positions.
|
|
916
|
+
*
|
|
917
|
+
* @param {number} availableFunds - Free funds not yet allocated
|
|
918
|
+
* @param {number} totalGridAllocation - Sum of all existing grid order sizes
|
|
919
|
+
* @param {number} orderCount - Number of orders to size
|
|
920
|
+
* @param {string} orderType - Order type (BUY or SELL)
|
|
921
|
+
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
922
|
+
* @param {number} [minSize=0] - Minimum size for each allocation
|
|
923
|
+
* @param {number} [precision=null] - Asset precision for quantization
|
|
924
|
+
* @returns {Array<number>} Array of order sizes
|
|
925
|
+
*/
|
|
926
|
+
function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config, minSize = 0, precision = null) {
|
|
927
|
+
if (orderCount <= 0)
|
|
928
|
+
return [];
|
|
929
|
+
const totalFunds = availableFunds + totalGridAllocation;
|
|
930
|
+
if (!Number.isFinite(totalFunds) || totalFunds <= 0)
|
|
931
|
+
return new Array(orderCount).fill(0);
|
|
932
|
+
const { incrementPercent, weightDistribution } = config;
|
|
933
|
+
const incrementFactor = incrementPercent / 100;
|
|
934
|
+
const weight = (orderType === ORDER_TYPES.SELL) ? weightDistribution.sell : weightDistribution.buy;
|
|
935
|
+
const reverse = (orderType === ORDER_TYPES.BUY);
|
|
936
|
+
return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse, minSize, precision);
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
|
|
940
|
+
* Measures how much the current grid differs from the calculated ideal.
|
|
941
|
+
* Used to determine if grid recalculation is needed.
|
|
942
|
+
*
|
|
943
|
+
* RMS quadratically penalizes large errors and unmatched orders (treated as 100% error).
|
|
944
|
+
* Default 14.3% RMS threshold allows ~3.2% average error concentrated in few orders.
|
|
945
|
+
* See README GRID RECALCULATION section for threshold interpretation table.
|
|
946
|
+
*
|
|
947
|
+
* @param {Array<Object>} calculatedOrders - Ideal/calculated order grid
|
|
948
|
+
* @param {Array<Object>} persistedOrders - Current/persisted order grid
|
|
949
|
+
* @param {string} [sideName='unknown'] - Side name for logging (buy/sell)
|
|
950
|
+
* @returns {number} RMS divergence metric (0 = perfect match, higher = more divergence)
|
|
951
|
+
*/
|
|
952
|
+
function calculateGridSideDivergenceMetric(calculatedOrders, persistedOrders, sideName = 'unknown') {
|
|
953
|
+
if (!Array.isArray(calculatedOrders) || !Array.isArray(persistedOrders))
|
|
954
|
+
return 0;
|
|
955
|
+
if (calculatedOrders.length === 0 && persistedOrders.length === 0)
|
|
956
|
+
return 0;
|
|
957
|
+
const persistedMap = new Map(persistedOrders.filter(o => o.id).map(o => [o.id, o]));
|
|
958
|
+
let sumSquaredDiff = 0;
|
|
959
|
+
let matchCount = 0;
|
|
960
|
+
let unmatchedCount = 0;
|
|
961
|
+
for (const calcOrder of calculatedOrders) {
|
|
962
|
+
const persOrder = persistedMap.get(calcOrder.id);
|
|
963
|
+
if (persOrder) {
|
|
964
|
+
const currentSize = toFiniteNumber(persOrder.size);
|
|
965
|
+
const idealSize = toFiniteNumber(calcOrder.size);
|
|
966
|
+
if (idealSize > 0) {
|
|
967
|
+
const relativeDiff = (currentSize - idealSize) / idealSize;
|
|
968
|
+
sumSquaredDiff += relativeDiff * relativeDiff;
|
|
969
|
+
matchCount++;
|
|
970
|
+
}
|
|
971
|
+
else if (currentSize > 0) {
|
|
972
|
+
sumSquaredDiff += 1.0;
|
|
973
|
+
matchCount++;
|
|
974
|
+
}
|
|
975
|
+
else {
|
|
976
|
+
matchCount++;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
else {
|
|
980
|
+
sumSquaredDiff += 1.0;
|
|
981
|
+
unmatchedCount++;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
for (const persOrder of persistedOrders) {
|
|
985
|
+
if (!calculatedOrders.some(c => c.id === persOrder.id)) {
|
|
986
|
+
sumSquaredDiff += 1.0;
|
|
987
|
+
unmatchedCount++;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
const totalOrders = matchCount + unmatchedCount;
|
|
991
|
+
return totalOrders > 0 ? Math.sqrt(sumSquaredDiff / totalOrders) : 0;
|
|
992
|
+
}
|
|
993
|
+
// ================================================================================
|
|
994
|
+
// SECTION 10: VALIDATION HELPERS
|
|
995
|
+
// ================================================================================
|
|
996
|
+
/**
|
|
997
|
+
* Calculate estimated BTS order creation fees for a number of orders.
|
|
998
|
+
* Works for all pairs — returns the BTS fee budget needed for order operations.
|
|
999
|
+
*
|
|
1000
|
+
* @param {string} assetA - First asset symbol
|
|
1001
|
+
* @param {string} assetB - Second asset symbol (unused in calculation, kept for signature compat)
|
|
1002
|
+
* @param {number} totalOrders - Number of orders to create
|
|
1003
|
+
* @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
|
|
1004
|
+
* @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
|
|
1005
|
+
*/
|
|
1006
|
+
function calculateOrderCreationFees(assetA, assetB, totalOrders, feeMultiplier = FEE_PARAMETERS.BTS_RESERVATION_MULTIPLIER) {
|
|
1007
|
+
try {
|
|
1008
|
+
if (totalOrders > 0) {
|
|
1009
|
+
const btsFeeData = getAssetFees('BTS');
|
|
1010
|
+
return btsFeeData.createFee * totalOrders * feeMultiplier;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
catch (err) {
|
|
1014
|
+
mathLogger.warn(`calculateOrderCreationFees: fee cache unavailable for ${assetA}/${assetB}: ${err.message}. Using fallback fee.`);
|
|
1015
|
+
return FEE_PARAMETERS.BTS_FALLBACK_FEE;
|
|
1016
|
+
}
|
|
1017
|
+
return 0;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Deduct order fees from available buy/sell funds.
|
|
1021
|
+
* If BTS is the buy asset, deducts from buyFunds; if sell asset, deducts from sellFunds.
|
|
1022
|
+
*
|
|
1023
|
+
* @param {number} buyFunds - Available buy-side funds
|
|
1024
|
+
* @param {number} sellFunds - Available sell-side funds
|
|
1025
|
+
* @param {number} fees - Fee amount to deduct
|
|
1026
|
+
* @param {Object} config - Configuration with assetA and assetB
|
|
1027
|
+
* @param {Object} [logger=null] - Optional logger for logging deductions
|
|
1028
|
+
* @returns {Object} Updated funds object {buyFunds, sellFunds}
|
|
1029
|
+
*/
|
|
1030
|
+
function deductOrderFeesFromFunds(buyFunds, sellFunds, fees, config, logger = null) {
|
|
1031
|
+
let finalBuy = buyFunds;
|
|
1032
|
+
let finalSell = sellFunds;
|
|
1033
|
+
if (fees > 0) {
|
|
1034
|
+
if (config?.assetB === 'BTS') {
|
|
1035
|
+
finalBuy = Math.max(0, buyFunds - fees);
|
|
1036
|
+
logger?.log?.(`Reduced available BTS (buy) funds by ${Format.formatAmount8(fees)}`, 'info');
|
|
1037
|
+
}
|
|
1038
|
+
else if (config?.assetA === 'BTS') {
|
|
1039
|
+
finalSell = Math.max(0, sellFunds - fees);
|
|
1040
|
+
logger?.log?.(`Reduced available BTS (sell) funds by ${Format.formatAmount8(fees)}`, 'info');
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
return { buyFunds: finalBuy, sellFunds: finalSell };
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* Calculate how much input asset to swap into a constant-product AMM pool
|
|
1047
|
+
* to receive a target amount of output asset.
|
|
1048
|
+
*
|
|
1049
|
+
* Formula: k = reserveIn * reserveOut
|
|
1050
|
+
* newReserveOut = reserveOut - targetReceive
|
|
1051
|
+
* newReserveIn = k / newReserveOut
|
|
1052
|
+
* sellAmount = newReserveIn - reserveIn
|
|
1053
|
+
*
|
|
1054
|
+
* Caps swap at 50% of pool reserves to prevent extreme slippage.
|
|
1055
|
+
*
|
|
1056
|
+
* @param {number} targetReceive - Desired amount of output asset
|
|
1057
|
+
* @param {number} poolReserveOut - Pool reserve of output asset
|
|
1058
|
+
* @param {number} poolReserveIn - Pool reserve of input asset
|
|
1059
|
+
* @returns {number} Amount of input asset to sell
|
|
1060
|
+
*/
|
|
1061
|
+
function calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) {
|
|
1062
|
+
if (targetReceive <= 0 || poolReserveOut <= 0 || poolReserveIn <= 0)
|
|
1063
|
+
return 0;
|
|
1064
|
+
let effectiveTarget = targetReceive;
|
|
1065
|
+
if (effectiveTarget >= poolReserveOut * 0.5) {
|
|
1066
|
+
effectiveTarget = poolReserveOut * 0.5;
|
|
1067
|
+
}
|
|
1068
|
+
const k = poolReserveIn * poolReserveOut;
|
|
1069
|
+
const newReserveOut = poolReserveOut - effectiveTarget;
|
|
1070
|
+
if (newReserveOut <= 0)
|
|
1071
|
+
return 0;
|
|
1072
|
+
const newReserveIn = k / newReserveOut;
|
|
1073
|
+
return newReserveIn - poolReserveIn;
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Calculate the spread gap size (number of empty slots between BUY and SELL rails).
|
|
1077
|
+
* Used by both grid creation and strategy rebalancing to keep spread math consistent.
|
|
1078
|
+
*
|
|
1079
|
+
* @param {number} incrementPercent - Grid increment percentage
|
|
1080
|
+
* @param {number} targetSpreadPercent - Target spread percentage
|
|
1081
|
+
* @param {Object} GRID_LIMITS - Grid limits constants (optional, uses defaults)
|
|
1082
|
+
* @returns {number} Number of gap slots
|
|
1083
|
+
*/
|
|
1084
|
+
function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {}) {
|
|
1085
|
+
const DEFAULT_INCREMENT = Number(DEFAULT_CONFIG.incrementPercent);
|
|
1086
|
+
const MIN_SPREAD_FACTOR = gridLimits.MIN_SPREAD_FACTOR ?? GRID_LIMITS.MIN_SPREAD_FACTOR;
|
|
1087
|
+
const MIN_SPREAD_ORDERS = gridLimits.MIN_SPREAD_ORDERS ?? GRID_LIMITS.MIN_SPREAD_ORDERS;
|
|
1088
|
+
const safeIncrement = (Number.isFinite(incrementPercent) && incrementPercent > 0) ? incrementPercent : DEFAULT_INCREMENT;
|
|
1089
|
+
const step = 1 + (safeIncrement / 100);
|
|
1090
|
+
const minSpreadPercent = safeIncrement * MIN_SPREAD_FACTOR;
|
|
1091
|
+
const effectiveTargetSpread = Math.max(targetSpreadPercent || 0, minSpreadPercent);
|
|
1092
|
+
const requiredSteps = Math.ceil(Math.log(1 + (effectiveTargetSpread / 100)) / Math.log(step));
|
|
1093
|
+
return Math.max(MIN_SPREAD_ORDERS, requiredSteps - 1);
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Clamp a value between min and max bounds.
|
|
1097
|
+
* @param {number} value - The value to clamp
|
|
1098
|
+
* @param {number} min - Lower bound
|
|
1099
|
+
* @param {number} max - Upper bound
|
|
1100
|
+
* @returns {number}
|
|
1101
|
+
*/
|
|
1102
|
+
function clamp(value, min, max) {
|
|
1103
|
+
return Math.max(min, Math.min(max, value));
|
|
1104
|
+
}
|
|
1105
|
+
/**
|
|
1106
|
+
* Safely clone a weight distribution object.
|
|
1107
|
+
* Validates numeric sell/buy values and falls back to a base object if provided.
|
|
1108
|
+
* Returns null if neither primary nor base yields valid numbers.
|
|
1109
|
+
*
|
|
1110
|
+
* @param {Object|null} weightDistribution - Primary weights (e.g. { sell, buy })
|
|
1111
|
+
* @param {Object|null} base - Fallback weights if primary is missing/invalid
|
|
1112
|
+
* @returns {{sell:number,buy:number}|null}
|
|
1113
|
+
*/
|
|
1114
|
+
function cloneWeightDistribution(weightDistribution, base = null) {
|
|
1115
|
+
const source = (weightDistribution && typeof weightDistribution === 'object')
|
|
1116
|
+
? weightDistribution
|
|
1117
|
+
: (base && typeof base === 'object' ? base : null);
|
|
1118
|
+
if (!source)
|
|
1119
|
+
return null;
|
|
1120
|
+
const sell = Number(source.sell);
|
|
1121
|
+
const buy = Number(source.buy);
|
|
1122
|
+
if (!Number.isFinite(sell) || !Number.isFinite(buy))
|
|
1123
|
+
return null;
|
|
1124
|
+
return { sell, buy };
|
|
1125
|
+
}
|
|
1126
|
+
module.exports = {
|
|
1127
|
+
calculateGapSlots,
|
|
1128
|
+
isPercentageString,
|
|
1129
|
+
isPositiveNumber,
|
|
1130
|
+
isPositiveNumberOrPercent,
|
|
1131
|
+
isPositiveInt,
|
|
1132
|
+
parsePercentageString,
|
|
1133
|
+
toDecimal,
|
|
1134
|
+
resolveRelativePrice,
|
|
1135
|
+
isExplicitZeroAllocation,
|
|
1136
|
+
getPrecision,
|
|
1137
|
+
computeChainFundTotals,
|
|
1138
|
+
calculateAvailableFundsValue,
|
|
1139
|
+
getGridBestPrices,
|
|
1140
|
+
calculateSpreadFromOrders,
|
|
1141
|
+
resolveConfigValue,
|
|
1142
|
+
resolveConfigValueWithRegistry,
|
|
1143
|
+
hasValidAccountTotals,
|
|
1144
|
+
blockchainToFloat,
|
|
1145
|
+
floatToBlockchainInt,
|
|
1146
|
+
quantizeFloat,
|
|
1147
|
+
normalizeInt,
|
|
1148
|
+
getPrecisionByOrderType,
|
|
1149
|
+
getPrecisionForSide,
|
|
1150
|
+
getPrecisionsForManager,
|
|
1151
|
+
getPrecisionSlack,
|
|
1152
|
+
calculatePriceTolerance,
|
|
1153
|
+
validateOrderAmountsWithinLimits,
|
|
1154
|
+
getMinOrderSize,
|
|
1155
|
+
getDustThresholdFactor,
|
|
1156
|
+
getSingleDustThreshold,
|
|
1157
|
+
getDoubleDustThreshold,
|
|
1158
|
+
getMinAbsoluteOrderSize,
|
|
1159
|
+
validateOrderSize,
|
|
1160
|
+
getAssetFees,
|
|
1161
|
+
allocateFundsByWeights,
|
|
1162
|
+
calculateOrderSizes,
|
|
1163
|
+
calculateRotationOrderSizes,
|
|
1164
|
+
calculateGridSideDivergenceMetric,
|
|
1165
|
+
calculateOrderCreationFees,
|
|
1166
|
+
deductOrderFeesFromFunds,
|
|
1167
|
+
calculateSwapInAmount,
|
|
1168
|
+
_setFeeCache,
|
|
1169
|
+
cloneWeightDistribution,
|
|
1170
|
+
clamp
|
|
1171
|
+
};
|
|
1172
|
+
//# sourceMappingURL=math.js.map
|