dexbot 1.6.7 → 1.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (626) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/README.md +3 -3
  3. package/analysis/README.md +2 -3
  4. package/analysis/tradingview/README.md +78 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
  10. package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
  11. package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
  12. package/dist/analysis/tradingview/grid_reset_config.js +235 -0
  13. package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
  14. package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
  16. package/dist/dexbot.js +55 -16
  17. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  18. package/dist/market_adapter/core/market_adapter_service.js +239 -20
  19. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  20. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  21. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  22. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  23. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
  24. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
  25. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  26. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  27. package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
  28. package/dist/market_adapter/inputs/window_cache.js +302 -48
  29. package/dist/market_adapter/interval_utils.d.ts +18 -1
  30. package/dist/market_adapter/interval_utils.js +31 -1
  31. package/dist/market_adapter/market_adapter.d.ts +158 -2
  32. package/dist/market_adapter/market_adapter.js +399 -65
  33. package/dist/market_adapter/test_helpers.d.ts +2 -2
  34. package/dist/market_adapter/test_helpers.js +2 -2
  35. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  36. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  37. package/dist/modules/account_bots.js +10 -0
  38. package/dist/modules/account_orders.d.ts +24 -2
  39. package/dist/modules/account_orders.js +41 -4
  40. package/dist/modules/bot_settings.js +10 -1
  41. package/dist/modules/config.d.ts +7 -0
  42. package/dist/modules/config.js +2 -0
  43. package/dist/modules/constants.d.ts +16 -4
  44. package/dist/modules/constants.js +144 -38
  45. package/dist/modules/dexbot_class.d.ts +6 -76
  46. package/dist/modules/dexbot_class.js +0 -32
  47. package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
  48. package/dist/modules/dexbot_cow_runtime.js +4 -87
  49. package/dist/modules/dexbot_maintenance_runtime.d.ts +15 -1
  50. package/dist/modules/dexbot_maintenance_runtime.js +59 -11
  51. package/dist/modules/dexbot_startup_runtime.js +73 -20
  52. package/dist/modules/dexbot_state_recovery.d.ts +6 -0
  53. package/dist/modules/dexbot_state_recovery.js +21 -0
  54. package/dist/modules/order/async_lock.d.ts +8 -0
  55. package/dist/modules/order/async_lock.js +15 -0
  56. package/dist/modules/order/genesis_policy.d.ts +162 -0
  57. package/dist/modules/order/genesis_policy.js +267 -0
  58. package/dist/modules/order/grid.js +172 -160
  59. package/dist/modules/order/grid_reconcile.d.ts +9 -0
  60. package/dist/modules/order/grid_reconcile.js +13 -4
  61. package/dist/modules/order/grid_reconcile_internal.js +2 -2
  62. package/dist/modules/order/manager.d.ts +4 -0
  63. package/dist/modules/order/manager.js +14 -1
  64. package/dist/modules/order/sync_engine.d.ts +19 -0
  65. package/dist/modules/order/sync_engine.js +284 -344
  66. package/dist/modules/order/utils/math.d.ts +22 -1
  67. package/dist/modules/order/utils/math.js +64 -1
  68. package/dist/modules/order/utils/order.d.ts +43 -58
  69. package/dist/modules/order/utils/order.js +220 -197
  70. package/dist/modules/order/utils/system.js +8 -1
  71. package/dist/modules/paths.d.ts +1 -0
  72. package/dist/modules/paths.js +1 -0
  73. package/dist/modules/version_notice.d.ts +311 -0
  74. package/dist/modules/version_notice.js +709 -0
  75. package/dist/pm2.js +16 -0
  76. package/dist/unlock.js +28 -0
  77. package/docs/BITSHARES_ONBOARDING.md +8 -1
  78. package/docs/COW_INVARIANTS.md +3 -2
  79. package/docs/DEXBOT_COMPARISON.md +4 -4
  80. package/docs/EVOLUTION.md +22 -20
  81. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  82. package/docs/GRID_PRICE_INVARIANT.md +149 -31
  83. package/docs/GRID_RECALCULATION.md +18 -2
  84. package/docs/README.md +3 -1
  85. package/docs/WORKFLOW.md +16 -5
  86. package/market_adapter/README.md +29 -1
  87. package/modules/README.md +18 -1
  88. package/package.json +13 -5
  89. package/scripts/README.md +28 -2
  90. package/scripts/clear-all.sh +13 -4
  91. package/scripts/clear-logs.sh +13 -4
  92. package/scripts/clear-market-adapter.sh +6 -0
  93. package/scripts/clear-orders.sh +5 -0
  94. package/scripts/lib/dexbot-paths.sh +108 -0
  95. package/tests/README.md +11 -3
  96. package/analysis/account_resolver.ts +0 -161
  97. package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
  98. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
  99. package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
  100. package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
  101. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
  102. package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
  103. package/analysis/analyze_dynamic_weight.ts +0 -243
  104. package/analysis/analyze_kalman.ts +0 -157
  105. package/analysis/analyze_regime.ts +0 -158
  106. package/analysis/analyze_regime_windows.ts +0 -470
  107. package/analysis/analyze_risk_profile.ts +0 -199
  108. package/analysis/analyze_trade_heatmap.ts +0 -362
  109. package/analysis/analyze_volatility.ts +0 -182
  110. package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
  111. package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
  112. package/analysis/bot_fitting/shared_utils.ts +0 -52
  113. package/analysis/bot_key_utils.ts +0 -426
  114. package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
  115. package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
  116. package/analysis/chain_pool.ts +0 -47
  117. package/analysis/chart_css.ts +0 -62
  118. package/analysis/chart_ui.ts +0 -105
  119. package/analysis/chart_utils.ts +0 -210
  120. package/analysis/fills_source.ts +0 -228
  121. package/analysis/grid_correction_check.ts +0 -786
  122. package/analysis/math_utils.ts +0 -53
  123. package/analysis/price_sources.ts +0 -136
  124. package/analysis/resolve_bot_accounts.ts +0 -199
  125. package/analysis/resolve_source.ts +0 -99
  126. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
  127. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
  128. package/analysis/trade_profitability.ts +0 -1335
  129. package/analysis/tradingview/analyze_tradingview.ts +0 -280
  130. package/analysis/tradingview/h-bts_tradingview.html +0 -1570
  131. package/analysis/tradingview/t-bts_tradingview.html +0 -1570
  132. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
  133. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
  134. package/analysis/trend_detection/hurst_analyzer.ts +0 -7
  135. package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
  136. package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
  137. package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
  138. package/analysis/trend_detection/package.json +0 -23
  139. package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
  140. package/analysis/trend_detection/regime_chart_generator.ts +0 -338
  141. package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
  142. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
  143. package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
  144. package/analysis/tsconfig.json +0 -29
  145. package/claw/tests/package.json +0 -3
  146. package/claw/tests/test_claw_bridge.ts +0 -570
  147. package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
  148. package/claw/tests/test_claw_chain_layer.ts +0 -739
  149. package/claw/tests/test_claw_data_flow.ts +0 -525
  150. package/claw/tests/test_claw_domain_logic.ts +0 -471
  151. package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
  152. package/claw/tests/test_claw_mcp_transport.ts +0 -243
  153. package/claw/tests/test_claw_regressions.ts +0 -711
  154. package/claw/tests/test_claw_skill_generation.ts +0 -103
  155. package/claw/tests/test_claw_state_store.ts +0 -44
  156. package/claw/tests/test_dexbot_profiles.ts +0 -654
  157. package/claw/tests/test_memu_bridge.ts +0 -189
  158. package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
  159. package/claw/tests/test_position_health.ts +0 -343
  160. package/claw/tests/test_position_manager.ts +0 -429
  161. package/claw/tests/test_position_manager_watch_health.ts +0 -100
  162. package/claw/tests/test_short_mpa_strategy.ts +0 -232
  163. package/dist/analysis/account_resolver.d.ts.map +0 -1
  164. package/dist/analysis/account_resolver.js.map +0 -1
  165. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  166. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  167. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  168. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  169. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  170. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  171. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  172. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  173. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  174. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  175. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  176. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  177. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  178. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  179. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  180. package/dist/analysis/analyze_kalman.js.map +0 -1
  181. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  182. package/dist/analysis/analyze_regime.js.map +0 -1
  183. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  184. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  185. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  186. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  187. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  188. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  189. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  190. package/dist/analysis/analyze_volatility.js.map +0 -1
  191. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  192. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  193. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  194. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  195. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  196. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  197. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  198. package/dist/analysis/bot_key_utils.js.map +0 -1
  199. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  200. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  201. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  202. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  203. package/dist/analysis/chain_pool.d.ts.map +0 -1
  204. package/dist/analysis/chain_pool.js.map +0 -1
  205. package/dist/analysis/chart_css.d.ts.map +0 -1
  206. package/dist/analysis/chart_css.js.map +0 -1
  207. package/dist/analysis/chart_ui.d.ts.map +0 -1
  208. package/dist/analysis/chart_ui.js.map +0 -1
  209. package/dist/analysis/chart_utils.d.ts.map +0 -1
  210. package/dist/analysis/chart_utils.js.map +0 -1
  211. package/dist/analysis/fills_source.d.ts.map +0 -1
  212. package/dist/analysis/fills_source.js.map +0 -1
  213. package/dist/analysis/grid_correction_check.d.ts.map +0 -1
  214. package/dist/analysis/grid_correction_check.js.map +0 -1
  215. package/dist/analysis/math_utils.d.ts.map +0 -1
  216. package/dist/analysis/math_utils.js.map +0 -1
  217. package/dist/analysis/price_sources.d.ts.map +0 -1
  218. package/dist/analysis/price_sources.js.map +0 -1
  219. package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
  220. package/dist/analysis/resolve_bot_accounts.js.map +0 -1
  221. package/dist/analysis/resolve_source.d.ts.map +0 -1
  222. package/dist/analysis/resolve_source.js.map +0 -1
  223. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  224. package/dist/analysis/trade_profitability.js.map +0 -1
  225. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  226. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  227. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
  228. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
  229. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  230. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  231. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
  232. package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
  233. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  234. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  235. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
  236. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
  237. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
  238. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
  239. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
  240. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
  241. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  242. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  243. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  244. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  245. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
  246. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  247. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  248. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  249. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
  250. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  251. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  252. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
  253. package/dist/bot.d.ts.map +0 -1
  254. package/dist/bot.js.map +0 -1
  255. package/dist/credential-daemon.d.ts.map +0 -1
  256. package/dist/credential-daemon.js.map +0 -1
  257. package/dist/dexbot.d.ts.map +0 -1
  258. package/dist/dexbot.js.map +0 -1
  259. package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
  260. package/dist/market_adapter/ama_signal_runner.js.map +0 -1
  261. package/dist/market_adapter/candle_utils.d.ts.map +0 -1
  262. package/dist/market_adapter/candle_utils.js.map +0 -1
  263. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
  264. package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
  265. package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
  266. package/dist/market_adapter/core/config_normalizers.js.map +0 -1
  267. package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
  268. package/dist/market_adapter/core/kibana_candles.js.map +0 -1
  269. package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
  270. package/dist/market_adapter/core/kibana_client.js.map +0 -1
  271. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
  272. package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
  273. package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
  274. package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
  275. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
  276. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
  277. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
  278. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
  279. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
  280. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
  281. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
  282. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
  283. package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
  284. package/dist/market_adapter/core/strategies/ama.js.map +0 -1
  285. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
  286. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
  287. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
  288. package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
  289. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
  290. package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
  291. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
  292. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
  293. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
  294. package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
  295. package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
  296. package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
  297. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
  298. package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
  299. package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
  300. package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
  301. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
  302. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
  303. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
  304. package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
  305. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
  306. package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
  307. package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
  308. package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
  309. package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
  310. package/dist/market_adapter/inputs/window_cache.js.map +0 -1
  311. package/dist/market_adapter/interval_utils.d.ts.map +0 -1
  312. package/dist/market_adapter/interval_utils.js.map +0 -1
  313. package/dist/market_adapter/log_format.d.ts.map +0 -1
  314. package/dist/market_adapter/log_format.js.map +0 -1
  315. package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
  316. package/dist/market_adapter/lp_chart_core.js.map +0 -1
  317. package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
  318. package/dist/market_adapter/lp_chart_runner.js.map +0 -1
  319. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
  320. package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
  321. package/dist/market_adapter/market_adapter.d.ts.map +0 -1
  322. package/dist/market_adapter/market_adapter.js.map +0 -1
  323. package/dist/market_adapter/test_helpers.d.ts.map +0 -1
  324. package/dist/market_adapter/test_helpers.js.map +0 -1
  325. package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
  326. package/dist/market_adapter/utils/adapter_client.js.map +0 -1
  327. package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
  328. package/dist/market_adapter/utils/atomic_write.js.map +0 -1
  329. package/dist/market_adapter/utils/chain.d.ts.map +0 -1
  330. package/dist/market_adapter/utils/chain.js.map +0 -1
  331. package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
  332. package/dist/market_adapter/utils/data_discovery.js.map +0 -1
  333. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
  334. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
  335. package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
  336. package/dist/market_adapter/utils/file_lock.js.map +0 -1
  337. package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
  338. package/dist/market_adapter/utils/native_history.js.map +0 -1
  339. package/dist/modules/account_bots.d.ts.map +0 -1
  340. package/dist/modules/account_bots.js.map +0 -1
  341. package/dist/modules/account_orders.d.ts.map +0 -1
  342. package/dist/modules/account_orders.js.map +0 -1
  343. package/dist/modules/authority_resolver.d.ts.map +0 -1
  344. package/dist/modules/authority_resolver.js.map +0 -1
  345. package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
  346. package/dist/modules/bitshares-native/chain_client.js.map +0 -1
  347. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
  348. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
  349. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
  350. package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
  351. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
  352. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
  353. package/dist/modules/bitshares-native/index.d.ts.map +0 -1
  354. package/dist/modules/bitshares-native/index.js.map +0 -1
  355. package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
  356. package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
  357. package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
  358. package/dist/modules/bitshares-native/resolvers.js.map +0 -1
  359. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
  360. package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
  361. package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
  362. package/dist/modules/bitshares-native/serial/index.js.map +0 -1
  363. package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
  364. package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
  365. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
  366. package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
  367. package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
  368. package/dist/modules/bitshares-native/serial/types.js.map +0 -1
  369. package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
  370. package/dist/modules/bitshares-native/signing_client.js.map +0 -1
  371. package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
  372. package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
  373. package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
  374. package/dist/modules/bitshares-native/transport.js.map +0 -1
  375. package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
  376. package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
  377. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
  378. package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
  379. package/dist/modules/bitshares_client.d.ts.map +0 -1
  380. package/dist/modules/bitshares_client.js.map +0 -1
  381. package/dist/modules/bot_defaults.d.ts.map +0 -1
  382. package/dist/modules/bot_defaults.js.map +0 -1
  383. package/dist/modules/bot_settings.d.ts.map +0 -1
  384. package/dist/modules/bot_settings.js.map +0 -1
  385. package/dist/modules/bots_file_lock.d.ts.map +0 -1
  386. package/dist/modules/bots_file_lock.js.map +0 -1
  387. package/dist/modules/broadcast_failure.d.ts.map +0 -1
  388. package/dist/modules/broadcast_failure.js.map +0 -1
  389. package/dist/modules/chain_keys.d.ts.map +0 -1
  390. package/dist/modules/chain_keys.js.map +0 -1
  391. package/dist/modules/chain_orders.d.ts.map +0 -1
  392. package/dist/modules/chain_orders.js.map +0 -1
  393. package/dist/modules/cli_colors.d.ts.map +0 -1
  394. package/dist/modules/cli_colors.js.map +0 -1
  395. package/dist/modules/cli_start_onboarding.d.ts.map +0 -1
  396. package/dist/modules/cli_start_onboarding.js.map +0 -1
  397. package/dist/modules/cli_start_output.d.ts.map +0 -1
  398. package/dist/modules/cli_start_output.js.map +0 -1
  399. package/dist/modules/config.d.ts.map +0 -1
  400. package/dist/modules/config.js.map +0 -1
  401. package/dist/modules/constants.d.ts.map +0 -1
  402. package/dist/modules/constants.js.map +0 -1
  403. package/dist/modules/cr_planner.d.ts.map +0 -1
  404. package/dist/modules/cr_planner.js.map +0 -1
  405. package/dist/modules/credential_policy.d.ts.map +0 -1
  406. package/dist/modules/credential_policy.js.map +0 -1
  407. package/dist/modules/credential_runtime.d.ts.map +0 -1
  408. package/dist/modules/credential_runtime.js.map +0 -1
  409. package/dist/modules/credential_session_cache.d.ts.map +0 -1
  410. package/dist/modules/credential_session_cache.js.map +0 -1
  411. package/dist/modules/credit_pricing.d.ts.map +0 -1
  412. package/dist/modules/credit_pricing.js.map +0 -1
  413. package/dist/modules/credit_runtime.d.ts.map +0 -1
  414. package/dist/modules/credit_runtime.js.map +0 -1
  415. package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
  416. package/dist/modules/crypto/browser_provider.js.map +0 -1
  417. package/dist/modules/crypto/index.d.ts.map +0 -1
  418. package/dist/modules/crypto/index.js.map +0 -1
  419. package/dist/modules/crypto/node_provider.d.ts.map +0 -1
  420. package/dist/modules/crypto/node_provider.js.map +0 -1
  421. package/dist/modules/crypto/provider.d.ts.map +0 -1
  422. package/dist/modules/crypto/provider.js.map +0 -1
  423. package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
  424. package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
  425. package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
  426. package/dist/modules/crypto/pure_scrypt.js.map +0 -1
  427. package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
  428. package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
  429. package/dist/modules/crypto/sync.d.ts.map +0 -1
  430. package/dist/modules/crypto/sync.js.map +0 -1
  431. package/dist/modules/daemon_node_health.d.ts.map +0 -1
  432. package/dist/modules/daemon_node_health.js.map +0 -1
  433. package/dist/modules/dexbot_class.d.ts.map +0 -1
  434. package/dist/modules/dexbot_class.js.map +0 -1
  435. package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
  436. package/dist/modules/dexbot_cow_runtime.js.map +0 -1
  437. package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
  438. package/dist/modules/dexbot_credential_client.js.map +0 -1
  439. package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
  440. package/dist/modules/dexbot_fill_runtime.js.map +0 -1
  441. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
  442. package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
  443. package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
  444. package/dist/modules/dexbot_startup_runtime.js.map +0 -1
  445. package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
  446. package/dist/modules/dexbot_state_recovery.js.map +0 -1
  447. package/dist/modules/env.d.ts.map +0 -1
  448. package/dist/modules/env.js.map +0 -1
  449. package/dist/modules/fund_registry.d.ts.map +0 -1
  450. package/dist/modules/fund_registry.js.map +0 -1
  451. package/dist/modules/general_settings.d.ts.map +0 -1
  452. package/dist/modules/general_settings.js.map +0 -1
  453. package/dist/modules/graceful_shutdown.d.ts.map +0 -1
  454. package/dist/modules/graceful_shutdown.js.map +0 -1
  455. package/dist/modules/grid_price_source.d.ts.map +0 -1
  456. package/dist/modules/grid_price_source.js.map +0 -1
  457. package/dist/modules/key_store.d.ts.map +0 -1
  458. package/dist/modules/key_store.js.map +0 -1
  459. package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
  460. package/dist/modules/launcher/adapter_requirement.js.map +0 -1
  461. package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
  462. package/dist/modules/launcher/bot_supervisor.js.map +0 -1
  463. package/dist/modules/launcher/child_env.d.ts.map +0 -1
  464. package/dist/modules/launcher/child_env.js.map +0 -1
  465. package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
  466. package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
  467. package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
  468. package/dist/modules/launcher/credential_daemon.js.map +0 -1
  469. package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
  470. package/dist/modules/launcher/credential_secret.js.map +0 -1
  471. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
  472. package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
  473. package/dist/modules/launcher/headless_password.d.ts.map +0 -1
  474. package/dist/modules/launcher/headless_password.js.map +0 -1
  475. package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
  476. package/dist/modules/launcher/launch_modes.js.map +0 -1
  477. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
  478. package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
  479. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
  480. package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
  481. package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
  482. package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
  483. package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
  484. package/dist/modules/launcher/runtime_entry.js.map +0 -1
  485. package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
  486. package/dist/modules/launcher/status_reporting.js.map +0 -1
  487. package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
  488. package/dist/modules/launcher/supervisor_control.js.map +0 -1
  489. package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
  490. package/dist/modules/market_adapter_whitelist.js.map +0 -1
  491. package/dist/modules/node_connect_policy.d.ts.map +0 -1
  492. package/dist/modules/node_connect_policy.js.map +0 -1
  493. package/dist/modules/node_failure_ledger.d.ts.map +0 -1
  494. package/dist/modules/node_failure_ledger.js.map +0 -1
  495. package/dist/modules/node_health_cache.d.ts.map +0 -1
  496. package/dist/modules/node_health_cache.js.map +0 -1
  497. package/dist/modules/node_manager.d.ts.map +0 -1
  498. package/dist/modules/node_manager.js.map +0 -1
  499. package/dist/modules/order/accounting.d.ts.map +0 -1
  500. package/dist/modules/order/accounting.js.map +0 -1
  501. package/dist/modules/order/async_lock.d.ts.map +0 -1
  502. package/dist/modules/order/async_lock.js.map +0 -1
  503. package/dist/modules/order/export.d.ts.map +0 -1
  504. package/dist/modules/order/export.js.map +0 -1
  505. package/dist/modules/order/format.d.ts.map +0 -1
  506. package/dist/modules/order/format.js.map +0 -1
  507. package/dist/modules/order/grid.d.ts.map +0 -1
  508. package/dist/modules/order/grid.js.map +0 -1
  509. package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
  510. package/dist/modules/order/grid_reconcile.js.map +0 -1
  511. package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
  512. package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
  513. package/dist/modules/order/index.d.ts.map +0 -1
  514. package/dist/modules/order/index.js.map +0 -1
  515. package/dist/modules/order/logger.d.ts.map +0 -1
  516. package/dist/modules/order/logger.js.map +0 -1
  517. package/dist/modules/order/logger_state.d.ts.map +0 -1
  518. package/dist/modules/order/logger_state.js.map +0 -1
  519. package/dist/modules/order/manager.d.ts.map +0 -1
  520. package/dist/modules/order/manager.js.map +0 -1
  521. package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
  522. package/dist/modules/order/processed_fill_store.js.map +0 -1
  523. package/dist/modules/order/strategy.d.ts.map +0 -1
  524. package/dist/modules/order/strategy.js.map +0 -1
  525. package/dist/modules/order/sync_engine.d.ts.map +0 -1
  526. package/dist/modules/order/sync_engine.js.map +0 -1
  527. package/dist/modules/order/utils/math.d.ts.map +0 -1
  528. package/dist/modules/order/utils/math.js.map +0 -1
  529. package/dist/modules/order/utils/order.d.ts.map +0 -1
  530. package/dist/modules/order/utils/order.js.map +0 -1
  531. package/dist/modules/order/utils/slot.d.ts.map +0 -1
  532. package/dist/modules/order/utils/slot.js.map +0 -1
  533. package/dist/modules/order/utils/system.d.ts.map +0 -1
  534. package/dist/modules/order/utils/system.js.map +0 -1
  535. package/dist/modules/order/utils/timeout.d.ts.map +0 -1
  536. package/dist/modules/order/utils/timeout.js.map +0 -1
  537. package/dist/modules/order/utils/validate.d.ts.map +0 -1
  538. package/dist/modules/order/utils/validate.js.map +0 -1
  539. package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
  540. package/dist/modules/order/utils/withPoolRef.js.map +0 -1
  541. package/dist/modules/order/working_grid.d.ts.map +0 -1
  542. package/dist/modules/order/working_grid.js.map +0 -1
  543. package/dist/modules/path_api.d.ts.map +0 -1
  544. package/dist/modules/path_api.js.map +0 -1
  545. package/dist/modules/paths.d.ts.map +0 -1
  546. package/dist/modules/paths.js.map +0 -1
  547. package/dist/modules/process_discovery.d.ts.map +0 -1
  548. package/dist/modules/process_discovery.js.map +0 -1
  549. package/dist/modules/runtime.d.ts.map +0 -1
  550. package/dist/modules/runtime.js.map +0 -1
  551. package/dist/modules/runtime_settings.d.ts.map +0 -1
  552. package/dist/modules/runtime_settings.js.map +0 -1
  553. package/dist/modules/settings_merge.d.ts.map +0 -1
  554. package/dist/modules/settings_merge.js.map +0 -1
  555. package/dist/modules/socket_json_client.d.ts.map +0 -1
  556. package/dist/modules/socket_json_client.js.map +0 -1
  557. package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
  558. package/dist/modules/storage/browser_adapter.js.map +0 -1
  559. package/dist/modules/storage/index.d.ts.map +0 -1
  560. package/dist/modules/storage/index.js.map +0 -1
  561. package/dist/modules/storage/node_adapter.d.ts.map +0 -1
  562. package/dist/modules/storage/node_adapter.js.map +0 -1
  563. package/dist/modules/storage/types.d.ts.map +0 -1
  564. package/dist/modules/storage/types.js.map +0 -1
  565. package/dist/modules/types.d.ts.map +0 -1
  566. package/dist/modules/types.js.map +0 -1
  567. package/dist/modules/utils/base58check.d.ts.map +0 -1
  568. package/dist/modules/utils/base58check.js.map +0 -1
  569. package/dist/modules/utils/build_dir.d.ts.map +0 -1
  570. package/dist/modules/utils/build_dir.js.map +0 -1
  571. package/dist/modules/utils/chain_logs.d.ts.map +0 -1
  572. package/dist/modules/utils/chain_logs.js.map +0 -1
  573. package/dist/modules/utils/errors.d.ts.map +0 -1
  574. package/dist/modules/utils/errors.js.map +0 -1
  575. package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
  576. package/dist/modules/utils/sanitize_key.js.map +0 -1
  577. package/dist/modules/utils/text_width.d.ts.map +0 -1
  578. package/dist/modules/utils/text_width.js.map +0 -1
  579. package/dist/modules/validate_profiles.d.ts.map +0 -1
  580. package/dist/modules/validate_profiles.js.map +0 -1
  581. package/dist/pm2.d.ts.map +0 -1
  582. package/dist/pm2.js.map +0 -1
  583. package/dist/scripts/analyze-credit.d.ts.map +0 -1
  584. package/dist/scripts/analyze-credit.js.map +0 -1
  585. package/dist/scripts/analyze-git.d.ts.map +0 -1
  586. package/dist/scripts/analyze-git.js.map +0 -1
  587. package/dist/scripts/analyze-orders.d.ts.map +0 -1
  588. package/dist/scripts/analyze-orders.js.map +0 -1
  589. package/dist/scripts/chart_command.d.ts.map +0 -1
  590. package/dist/scripts/chart_command.js.map +0 -1
  591. package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
  592. package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
  593. package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
  594. package/dist/scripts/diagnose-pool-history.js.map +0 -1
  595. package/dist/scripts/divergence-calc.d.ts.map +0 -1
  596. package/dist/scripts/divergence-calc.js.map +0 -1
  597. package/dist/scripts/dw.d.ts.map +0 -1
  598. package/dist/scripts/dw.js.map +0 -1
  599. package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
  600. package/dist/scripts/generate_lp_chart.js.map +0 -1
  601. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
  602. package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
  603. package/dist/scripts/native_release_gates.d.ts.map +0 -1
  604. package/dist/scripts/native_release_gates.js.map +0 -1
  605. package/dist/scripts/print_grid.d.ts.map +0 -1
  606. package/dist/scripts/print_grid.js.map +0 -1
  607. package/dist/scripts/run-tests.d.ts.map +0 -1
  608. package/dist/scripts/run-tests.js.map +0 -1
  609. package/dist/scripts/runner.d.ts.map +0 -1
  610. package/dist/scripts/runner.js.map +0 -1
  611. package/dist/scripts/sync-version.d.ts.map +0 -1
  612. package/dist/scripts/sync-version.js.map +0 -1
  613. package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
  614. package/dist/scripts/test-credit-renewal.js.map +0 -1
  615. package/dist/scripts/tv.d.ts.map +0 -1
  616. package/dist/scripts/tv.js.map +0 -1
  617. package/dist/scripts/update.d.ts.map +0 -1
  618. package/dist/scripts/update.js.map +0 -1
  619. package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
  620. package/dist/scripts/update_dist_freshness.js.map +0 -1
  621. package/dist/scripts/validate_bots.d.ts.map +0 -1
  622. package/dist/scripts/validate_bots.js.map +0 -1
  623. package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
  624. package/dist/scripts/verify-browser-bundle.js.map +0 -1
  625. package/dist/unlock.d.ts.map +0 -1
  626. package/dist/unlock.js.map +0 -1
@@ -1,3268 +0,0 @@
1
- 'use strict';
2
-
3
- import fs from 'node:fs';
4
- import { MARKET_ADAPTER } from '../../modules/constants.js';
5
- import { escapeHtml, serializeJsonForScript, UPLOT_SHARED_SCRIPT, embedFunctionSources, uplotInlineTags } from '../chart_utils.js';
6
- import { cursorCSS, uplotBgCSS } from '../chart_css.js';
7
- import { zoomResetScript } from '../chart_ui.js';
8
- import { normalizeCandle } from '../math_utils.js';
9
- import { PATHS } from '../../modules/paths.js';
10
- import { getStorage } from '../../modules/storage/index.js';
11
- const { readJSON } = getStorage();
12
- import { getErrorMessage } from '../../modules/utils/errors.js';
13
- import { parseRelativeMultiplier } from '../../modules/order/utils/math.js';
14
- import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
15
- import {
16
- resolveBaseBounds,
17
- computeAsymmetricBoundsMetrics,
18
- applyAsymmetricBounds,
19
- applyNarrowingSideGuard,
20
- } from '../../market_adapter/core/asymmetric_bounds.js';
21
-
22
-
23
- function inferBaseIntervalSeconds(candles: any[], fallback: any = 3600) {
24
- if (!Array.isArray(candles) || candles.length < 2) return fallback;
25
- const deltas: number[] = [];
26
- for (let i = 1; i < candles.length; i++) {
27
- const prev = Number(candles[i - 1]?.time);
28
- const curr = Number(candles[i]?.time);
29
- if (!Number.isFinite(prev) || !Number.isFinite(curr)) continue;
30
- const d = curr - prev;
31
- if (d > 0) deltas.push(d);
32
- }
33
- if (deltas.length === 0) return fallback;
34
- deltas.sort((a: any, b: any) => a - b);
35
- const mid = Math.floor(deltas.length / 2);
36
- const med = deltas.length % 2 === 0 ? (deltas[mid - 1] + deltas[mid]) / 2 : deltas[mid];
37
- return Math.max(60, Math.round(med));
38
- }
39
-
40
- function loadMarketProfiles(filePath: any = PATHS.PROFILES.MARKET_PROFILES_JSON) {
41
- if (!filePath || !fs.existsSync(filePath)) return null;
42
- try {
43
- return readJSON(filePath);
44
- } catch (err: any) {
45
- console.warn(`[WARN] Failed to parse ${filePath}: ${getErrorMessage(err)}. Falling back to built-in AMA defaults.`);
46
- return null;
47
- }
48
- }
49
-
50
- function findMarketProfile(profiles: any, meta: any = {}) {
51
- const entries = Array.isArray(profiles?.profiles) ? profiles.profiles : [];
52
- if (!entries.length) return null;
53
- const assetA = meta.assetA?.symbol || meta.assetA?.id || meta.assetA;
54
- const assetB = meta.assetB?.symbol || meta.assetB?.id || meta.assetB;
55
- const intervalSeconds = Number(meta.intervalSeconds);
56
- return entries.find((entry: any) => {
57
- if (!entry || typeof entry !== 'object') return false;
58
- if (assetA && assetB) {
59
- const matchesPair = (String(entry.assetA) === String(assetA) || String(entry.assetAId) === String(assetA))
60
- && (String(entry.assetB) === String(assetB) || String(entry.assetBId) === String(assetB));
61
- if (!matchesPair) return false;
62
- } else {
63
- return false;
64
- }
65
- if (Number.isFinite(intervalSeconds) && intervalSeconds > 0 && Number(entry.intervalSeconds) !== intervalSeconds) {
66
- return false;
67
- }
68
- return true;
69
- }) || null;
70
- }
71
-
72
- function resolveAmaDefaults({ meta, data, marketProfiles }: any = {}) {
73
- const amaDefaultsSource = MARKET_ADAPTER.AMAS.AMA3;
74
- const profile = findMarketProfile(marketProfiles, meta);
75
- const profileAmaKey = profile?.defaultAma && profile.amas && profile.amas[profile.defaultAma]
76
- ? profile.defaultAma
77
- : null;
78
- const profileAma = profileAmaKey ? profile.amas[profileAmaKey] : null;
79
- const source = data?.amaDefaults || profileAma || amaDefaultsSource;
80
- return {
81
- erPeriod: Math.max(1, Math.round(Number(data?.amaErPeriod ?? source.erPeriod))),
82
- fastPeriod: Number.isFinite(Number(data?.amaFastPeriod))
83
- ? Number(data.amaFastPeriod)
84
- : Number(source.fastPeriod),
85
- slowPeriod: Number.isFinite(Number(data?.amaSlowPeriod))
86
- ? Number(data.amaSlowPeriod)
87
- : Number(source.slowPeriod),
88
- };
89
- }
90
-
91
- const TRADINGVIEW_PREFS_KEY_PREFIX = 'dexbot2-tradingview-uplot-v3';
92
- const TRADINGVIEW_SYNC_KEY = 'dexbot2-tradingview-sync';
93
-
94
- function sanitizeStorageComponent(value: any, fallback: string) {
95
- // Objects (e.g. a meta asset node missing both id and symbol) stringify to
96
- // "[object Object]", which would collapse distinct assets onto one key.
97
- if (value == null || typeof value === 'object') return fallback;
98
- const raw = String(value).trim();
99
- const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^_+|_+$/g, '');
100
- return cleaned || fallback;
101
- }
102
-
103
- // Prefer asset ids over symbols: ids are immutable, symbols can be relabeled.
104
- function resolveChartStorageKey(meta: any = {}, baseIntervalSeconds: any = 0) {
105
- const pool = sanitizeStorageComponent(meta?.pool ?? meta?.poolId, 'nipool');
106
- const assetA = sanitizeStorageComponent(meta?.assetA?.id ?? meta?.assetA?.symbol ?? meta?.assetA, 'assetA');
107
- const assetB = sanitizeStorageComponent(meta?.assetB?.id ?? meta?.assetB?.symbol ?? meta?.assetB, 'assetB');
108
- const interval = Number(baseIntervalSeconds) > 0 ? Math.round(Number(baseIntervalSeconds)) : 0;
109
- return `${TRADINGVIEW_PREFS_KEY_PREFIX}:${pool}:${assetA}_${assetB}:${interval || 'base'}`;
110
- }
111
-
112
- function generateHTML(data: any, title: any = 'TradingView Style Research') {
113
- const rawCandles = Array.isArray(data.candles) ? data.candles : [];
114
- const candles = rawCandles.map(normalizeCandle).filter(Boolean);
115
- if (candles.length === 0) throw new Error('No candle data in input');
116
-
117
- const meta = data.meta || {};
118
- const baseIntervalSeconds = Number(meta.intervalSeconds) > 0
119
- ? Number(meta.intervalSeconds)
120
- : inferBaseIntervalSeconds(candles, 3600);
121
-
122
- const timeframes = [
123
- { label: '1h', seconds: 3600 },
124
- { label: '4h', seconds: 14400 },
125
- { label: '1d', seconds: 86400 },
126
- { label: '1w', seconds: 604800 },
127
- { label: '1M', seconds: 2592000, calendar: 'month' },
128
- ].map((item: any) => ({ ...item, enabled: item.seconds >= baseIntervalSeconds }));
129
-
130
- const defaultTimeframe = timeframes.find((item: any) => item.label === data.defaultTimeframe && item.enabled)
131
- || timeframes.find((item: any) => item.enabled)
132
- || timeframes[0];
133
-
134
- const marketProfiles = data.marketProfiles || loadMarketProfiles();
135
- const defaultAmaConfig = resolveAmaDefaults({ meta, data, marketProfiles });
136
- const rangeSlope = {
137
- lookbackBars: MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS,
138
- maxSlopePct: MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
139
- neutralZonePct: MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT,
140
- maxSlopeOffset: MARKET_ADAPTER.DYNAMIC_WEIGHT_ASYMMETRIC_OFFSET_CLAMP,
141
- maxAsymmetryFactor: MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MAX_ASYMMETRY_FACTOR,
142
- minScaleSlots: MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MIN_SCALE_SLOTS,
143
- clipPercentile: MARKET_ADAPTER.DYNAMIC_WEIGHT_CLIP_PERCENTILE,
144
- };
145
- function defaultRangeSpan(input: { rangeSpan?: unknown; grid?: { minPrice?: unknown; maxPrice?: unknown } | null }): number {
146
- const cli = Number(input.rangeSpan);
147
- if (Number.isFinite(cli)) return Math.min(2, Math.max(1.2, cli));
148
- const down = parseRelativeMultiplier(input.grid?.minPrice);
149
- const up = parseRelativeMultiplier(input.grid?.maxPrice);
150
- if (down != null && down > 1 && up != null && up > 1) return Math.min(2, Math.max(1.2, (down + up) / 2));
151
- const vd = Number(input.grid?.minPrice);
152
- const vu = Number(input.grid?.maxPrice);
153
- if (Number.isFinite(vd) && Number.isFinite(vu) && vd > 0 && vu > vd) {
154
- const ref = Math.sqrt(vd * vu);
155
- return Math.min(2, Math.max(1.2, (ref / vd + vu / ref) / 2));
156
- }
157
- return 1.55;
158
- }
159
- const defaults = {
160
- smaPeriod: Math.max(1, Math.round(data.smaPeriod ?? 500)),
161
- amaDefaults: defaultAmaConfig,
162
- smaEnabled: data.smaEnabled === true,
163
- amaEnabled: data.amaEnabled === true,
164
- vwapEnabled: data.vwapEnabled === true,
165
- vwapBars: Math.max(5, Math.round(data.vwapBars ?? 500)),
166
- priceScale: data.priceScale === 'linear' ? 'linear' : 'log',
167
- rangeEnabled: data.rangeEnabled === true,
168
- rangeScaleEnabled: data.rangeScaleEnabled === true,
169
- rangeWidthPct: Number.isFinite(Number(data.rangeWidthPct)) && Number(data.rangeWidthPct) > 0
170
- ? Number(data.rangeWidthPct)
171
- : 2,
172
- rangeSpan: defaultRangeSpan(data),
173
- grid: data.grid && data.grid.minPrice != null && data.grid.maxPrice != null ? {
174
- minPrice: data.grid.minPrice,
175
- maxPrice: data.grid.maxPrice,
176
- incrementPercent: Number(data.grid.incrementPercent) > 0 ? Number(data.grid.incrementPercent) : null,
177
- maxAsymmetryFactor: Number.isFinite(Number(data.grid.maxAsymmetryFactor)) && Number(data.grid.maxAsymmetryFactor) > 0
178
- ? Number(data.grid.maxAsymmetryFactor)
179
- : rangeSlope.maxAsymmetryFactor,
180
- } : null,
181
- rangeSlope,
182
- };
183
-
184
- const assetLabelA = meta.assetA?.symbol || meta.assetA?.id || 'Asset A';
185
- const assetLabelB = meta.assetB?.symbol || meta.assetB?.id || 'Asset B';
186
- const pairLabelNormal = `${assetLabelA}/${assetLabelB}`;
187
- const pairLabelInverse = `${assetLabelB}/${assetLabelA}`;
188
- const poolLabel = meta.pool ? `Pool ${String(meta.pool).replace(/^1\.19\./, '')}` : 'Pair';
189
- const intervalLabel = baseIntervalSeconds >= 86400
190
- ? `${Math.round(baseIntervalSeconds / 86400)}d`
191
- : `${Math.round(baseIntervalSeconds / 3600)}h`;
192
- const defaultPairMode = data.defaultPairMode === 'inverse' ? 'inverse' : 'normal';
193
- const storageKey = typeof data.storageKey === 'string' && data.storageKey.length > 0
194
- ? data.storageKey
195
- : resolveChartStorageKey(meta, baseIntervalSeconds);
196
-
197
- const payload = {
198
- storageKey,
199
- syncKey: TRADINGVIEW_SYNC_KEY,
200
- candles,
201
- timeframes,
202
- defaultTimeframe: defaultTimeframe.label,
203
- smaPeriod: defaults.smaPeriod,
204
- amaDefaults: defaultAmaConfig,
205
- smaEnabled: defaults.smaEnabled,
206
- amaEnabled: defaults.amaEnabled,
207
- vwapEnabled: defaults.vwapEnabled,
208
- vwapBars: defaults.vwapBars,
209
- priceScale: defaults.priceScale,
210
- rangeEnabled: defaults.rangeEnabled,
211
- rangeScaleEnabled: defaults.rangeScaleEnabled,
212
- rangeWidthPct: defaults.rangeWidthPct,
213
- rangeSpan: defaults.rangeSpan,
214
- grid: defaults.grid,
215
- orderBuys: Array.isArray((data as any).orders?.buys) ? (data as any).orders.buys.map(Number).filter(Number.isFinite) : [],
216
- orderSells: Array.isArray((data as any).orders?.sells) ? (data as any).orders.sells.map(Number).filter(Number.isFinite) : [],
217
- gridBounds: {
218
- low: Number.isFinite(Number((data as any).gridBounds?.low)) && Number((data as any).gridBounds.low) > 0 ? Number((data as any).gridBounds.low) : null,
219
- high: Number.isFinite(Number((data as any).gridBounds?.high)) && Number((data as any).gridBounds.high) > 0 ? Number((data as any).gridBounds.high) : null,
220
- },
221
- updateMarkerTsSec: Number((data as any).updateMarkerTsSec) > 0 ? Number((data as any).updateMarkerTsSec) : null,
222
- updateMarkerNewBars: Number((data as any).updateMarkerNewBars) || null,
223
- rangeSlope,
224
- defaultPairMode,
225
- assetLabelA,
226
- assetLabelB,
227
- pairLabelNormal,
228
- pairLabelInverse,
229
- poolLabel,
230
- intervalLabel,
231
- amaDefaultsSource: marketProfiles ? 'market_profiles' : 'constants',
232
- volumeIsCount: !!((meta as any)?.feed),
233
- };
234
-
235
- return `<!doctype html>
236
- <html lang="en">
237
- <head>
238
- <meta charset="utf-8">
239
- <meta name="color-scheme" content="dark">
240
- <meta name="darkreader-lock">
241
- <meta name="viewport" content="width=device-width, initial-scale=1">
242
- <title>${escapeHtml(title)}</title>
243
- ${uplotInlineTags()}
244
- <style>
245
- * { box-sizing: border-box; }
246
- :root { color-scheme: dark; }
247
- body {
248
- margin: 0;
249
- overflow: hidden;
250
- background: linear-gradient(180deg, #090d12 0%, #0b0f14 40%, #0a0c11 100%);
251
- color: #d7e0ea;
252
- font-family: Inter, "Segoe UI", system-ui, sans-serif;
253
- }
254
- #app { height: 100vh; display: flex; flex-direction: column; }
255
- #topbar {
256
- display: flex;
257
- justify-content: space-between;
258
- gap: 16px;
259
- padding: 12px 16px 10px;
260
- border-bottom: 1px solid #263241;
261
- background: rgba(15,19,26,0.94);
262
- backdrop-filter: blur(10px);
263
- }
264
- #brand { display: flex; flex-direction: column; gap: 4px; min-width: 240px; }
265
- #title { font-size: 15px; font-weight: 700; color: #f5f8fb; }
266
- #subtitle { font-size: 11px; color: #b9c6d4; text-transform: uppercase; letter-spacing: 0.6px; }
267
- #toolbar { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
268
- .toolbar-row { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px 12px; align-items: center; }
269
- .group { display: inline-flex; align-items: center; gap: 8px; padding-left: 12px; border-left: 1px solid #263241; }
270
- .group:first-child { padding-left: 0; border-left: 0; }
271
- .primary-toolbar-row .group { padding-left: 0; border-left: 0; }
272
- :root {
273
- --control-height: 36px;
274
- }
275
- .time-btn {
276
- appearance: none;
277
- border: 1px solid #263241;
278
- background: rgba(24,30,39,0.85);
279
- color: #8290a2;
280
- font-size: 11px;
281
- font-weight: 700;
282
- letter-spacing: 0.5px;
283
- text-transform: uppercase;
284
- padding: 7px 10px;
285
- border-radius: 8px;
286
- cursor: pointer;
287
- }
288
- .time-btn.active {
289
- color: #fff;
290
- border-color: rgba(94,161,255,0.85);
291
- background: linear-gradient(180deg, rgba(35,53,79,0.95), rgba(22,32,47,0.98));
292
- }
293
- .time-btn:disabled { opacity: 0.35; cursor: not-allowed; text-decoration: line-through; }
294
- .ama-preset-btn.active {
295
- color: #fff;
296
- border-color: rgba(250,204,21,0.85);
297
- background: linear-gradient(180deg, rgba(79,66,22,0.95), rgba(47,40,18,0.98));
298
- }
299
- .indicator {
300
- display: inline-flex;
301
- align-items: center;
302
- gap: 8px;
303
- min-height: var(--control-height);
304
- padding: 0 13px;
305
- border: 1px solid #263241;
306
- border-radius: 10px;
307
- background: rgba(20,25,33,0.86);
308
- }
309
- .indicator label {
310
- display: inline-flex;
311
- align-items: center;
312
- gap: 6px;
313
- min-height: var(--control-height);
314
- font-size: 11px;
315
- font-weight: 700;
316
- color: #d7e0ea;
317
- text-transform: uppercase;
318
- white-space: nowrap;
319
- }
320
- .indicator input[type="checkbox"] { width: 14px; height: 14px; accent-color: #5ea1ff; }
321
- .indicator input[type="number"], .indicator select {
322
- appearance: none;
323
- border: 1px solid #263241;
324
- background: rgba(10,14,19,0.92);
325
- color: #d7e0ea;
326
- border-radius: 8px;
327
- padding: 7px 10px;
328
- font-size: 11px;
329
- outline: none;
330
- width: 79px;
331
- min-width: 79px;
332
- height: calc(var(--control-height) - 8px);
333
- }
334
- .pair-toggle {
335
- appearance: none;
336
- width: 32px;
337
- height: 32px;
338
- display: inline-flex;
339
- align-items: center;
340
- justify-content: center;
341
- border: 1px solid #263241;
342
- border-radius: 999px;
343
- background: radial-gradient(circle at 30% 30%, rgba(94,161,255,0.18), rgba(10,14,19,0.96));
344
- color: #d7e0ea;
345
- cursor: pointer;
346
- padding: 0;
347
- box-shadow: inset 0 0 0 1px rgba(255,255,255,0.03);
348
- transition: transform 120ms ease, border-color 120ms ease, background 120ms ease, color 120ms ease;
349
- }
350
- .pair-toggle:hover {
351
- transform: translateY(-1px);
352
- border-color: rgba(94,161,255,0.85);
353
- color: #fff;
354
- }
355
- .pair-toggle:active {
356
- transform: translateY(0);
357
- }
358
- .pair-toggle svg {
359
- width: 17px;
360
- height: 17px;
361
- fill: currentColor;
362
- display: block;
363
- }
364
- .pair-toggle.is-inverse {
365
- color: #5ea1ff;
366
- border-color: rgba(94,161,255,0.45);
367
- }
368
- .indicator .step-stack {
369
- display: inline-flex;
370
- flex-direction: column;
371
- vertical-align: middle;
372
- margin-left: 2px;
373
- }
374
- .indicator .step-btn {
375
- appearance: none;
376
- display: block;
377
- width: 24px;
378
- height: 13px;
379
- border: 1px solid #3d4a5a;
380
- background: #1a2332;
381
- color: #8b949e;
382
- font-size: 9px;
383
- line-height: 1;
384
- cursor: pointer;
385
- padding: 0;
386
- margin: 0;
387
- }
388
- .indicator .step-btn:first-child {
389
- border-radius: 3px 3px 0 0;
390
- border-bottom: none;
391
- }
392
- .indicator .step-btn:last-child {
393
- border-radius: 0 0 3px 3px;
394
- }
395
- .indicator .step-btn:hover {
396
- background: #263241;
397
- }
398
- .indicator .step-btn:active {
399
- background: #3d4a5a;
400
- }
401
- .indicator input[type="text"] {
402
- appearance: none;
403
- border: 1px solid #263241;
404
- background: rgba(6,8,12,0.95);
405
- color: #d7e0ea;
406
- border-radius: 8px;
407
- padding: 7px 4px;
408
- font-size: 12px;
409
- outline: none;
410
- width: 44px;
411
- text-align: center;
412
- }
413
- .indicator input[type="text"]:focus {
414
- border-color: #5ea1ff;
415
- }
416
- #ama-fast {
417
- width: 38px;
418
- }
419
- .scale-toggle {
420
- appearance: none;
421
- min-width: 76px;
422
- height: 32px;
423
- display: inline-flex;
424
- align-items: center;
425
- justify-content: center;
426
- border: 1px solid #263241;
427
- border-radius: 999px;
428
- background: rgba(10,14,19,0.92);
429
- color: #d7e0ea;
430
- font-size: 11px;
431
- font-weight: 700;
432
- letter-spacing: 0.45px;
433
- text-transform: uppercase;
434
- cursor: pointer;
435
- padding: 0 11px;
436
- transition: transform 120ms ease, border-color 120ms ease, background 120ms ease, color 120ms ease;
437
- }
438
- .scale-toggle:hover {
439
- transform: translateY(-1px);
440
- border-color: rgba(94,161,255,0.85);
441
- color: #fff;
442
- }
443
- .scale-toggle:active {
444
- transform: translateY(0);
445
- }
446
- .scale-toggle.is-linear {
447
- color: #5ea1ff;
448
- border-color: rgba(94,161,255,0.45);
449
- }
450
- .reset-btn {
451
- appearance: none;
452
- border: 1px solid #263241;
453
- background: rgba(24,30,39,0.85);
454
- color: #d7e0ea;
455
- font-size: 11px;
456
- font-weight: 700;
457
- letter-spacing: 0.45px;
458
- text-transform: uppercase;
459
- padding: 6px 11px;
460
- border-radius: 8px;
461
- cursor: pointer;
462
- }
463
- .reset-btn:hover {
464
- border-color: rgba(94,161,255,0.85);
465
- color: #fff;
466
- }
467
- .indicator .tag { font-size: 10px; color: #8290a2; text-transform: uppercase; letter-spacing: 0.5px; }
468
- #chart-shell { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
469
- #price-chart { position: relative; flex: 1 1 auto; min-height: 0; }
470
- #volume-chart { position: relative; flex: 0 0 19%; min-height: 0; border-top: 1px solid #263241; }
471
- #legend {
472
- position: absolute;
473
- top: 14px;
474
- left: 14px;
475
- z-index: 4;
476
- padding: 10px 12px;
477
- min-width: 280px;
478
- max-width: calc(100vw - 28px);
479
- border: 1px solid #263241;
480
- border-radius: 12px;
481
- background: rgba(10,14,20,0.72);
482
- backdrop-filter: blur(10px);
483
- }
484
- .legend-line { display: flex; flex-wrap: wrap; gap: 10px 14px; align-items: center; font-size: 12px; }
485
- .legend-line + .legend-line { margin-top: 6px; padding-top: 6px; border-top: 1px solid rgba(255,255,255,0.06); }
486
- .legend-item { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
487
- .legend-dot { width: 10px; height: 10px; border-radius: 999px; flex: 0 0 auto; }
488
- .legend-label { color: #8290a2; text-transform: uppercase; letter-spacing: 0.45px; font-size: 12px; }
489
- .legend-value { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: #eef4fb; font-weight: 700; }
490
- .status { display: inline-flex; align-items: center; gap: 8px; font-size: 10px; color: #8290a2; text-transform: uppercase; letter-spacing: 0.5px; }
491
- .pill { border: 1px solid rgba(255,255,255,0.06); border-radius: 999px; padding: 4px 8px; background: rgba(255,255,255,0.03); }
492
- ${uplotBgCSS('#0b0f14')}
493
- ${cursorCSS()}
494
- @media (max-width: 980px) {
495
- #topbar { flex-direction: column; align-items: flex-start; }
496
- #toolbar { align-items: flex-start; }
497
- .toolbar-row { justify-content: flex-start; }
498
- .group { padding-left: 0; border-left: 0; flex-wrap: wrap; }
499
- #legend { min-width: 0; max-width: calc(100vw - 24px); }
500
- }
501
- </style>
502
- </head>
503
- <body>
504
- <div id="app">
505
- <div id="topbar">
506
- <div id="brand">
507
- <div id="title">${escapeHtml(title)}</div>
508
- <div id="subtitle">${escapeHtml(poolLabel)} · ${escapeHtml(pairLabelNormal)} · ${escapeHtml(intervalLabel)} base · indicators from 1h · volume · uPlot</div>
509
- </div>
510
- <div id="toolbar">
511
- <div class="toolbar-row primary-toolbar-row">
512
- <div class="group">
513
- <div class="indicator">
514
- <span class="tag">pair</span>
515
- <button type="button" class="pair-toggle${defaultPairMode === 'inverse' ? ' is-inverse' : ''}" id="pair-toggle" aria-label="Swap pair orientation" title="Swap pair orientation" data-pair-mode="${escapeHtml(defaultPairMode)}">
516
- <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
517
- <path d="M6.5 7H19v2H6.5v3L2 8.5 6.5 5v2Zm11 10H5v-2h12.5v-3L22 15.5 17.5 19v-2Z"/>
518
- </svg>
519
- </button>
520
- </div>
521
- <div class="indicator">
522
- <span class="tag">scale</span>
523
- <button type="button" class="scale-toggle${defaults.priceScale === 'linear' ? ' is-linear' : ''}" id="scale-toggle" data-scale="${escapeHtml(defaults.priceScale)}" aria-label="Toggle price scale" title="Toggle price scale">${defaults.priceScale === 'linear' ? 'Linear' : 'Log'}</button>
524
- </div>
525
- </div>
526
- <div class="group" id="tf-group">
527
- ${timeframes.map((item: any) => `<button class="time-btn${item.label === defaultTimeframe.label ? ' active' : ''}" data-timeframe="${escapeHtml(item.label)}"${item.enabled ? '' : ' disabled'}>${escapeHtml(item.label)}</button>`).join('')}
528
- </div>
529
- <div class="group">
530
- <div class="indicator">
531
- <label><input type="checkbox" id="sma-toggle"${defaults.smaEnabled ? ' checked' : ''}> SMA</label>
532
- <input type="text" inputmode="numeric" id="sma-period" value="${defaults.smaPeriod}">
533
- <span class="step-stack">
534
- <button type="button" class="step-btn" id="sma-period-inc">▲</button>
535
- <button type="button" class="step-btn" id="sma-period-dec">▼</button>
536
- </span>
537
- </div>
538
- <div class="indicator">
539
- <label><input type="checkbox" id="vwap-toggle"${defaults.vwapEnabled ? ' checked' : ''}> VWMA</label>
540
- <input type="text" inputmode="numeric" id="vwap-bars" value="${defaults.vwapBars}">
541
- <span class="step-stack">
542
- <button type="button" class="step-btn" id="vwap-bars-inc">▲</button>
543
- <button type="button" class="step-btn" id="vwap-bars-dec">▼</button>
544
- </span>
545
- </div>
546
- <div class="indicator"><label><input type="checkbox" id="volume-toggle" checked> Volume</label> <button type="button" class="reset-btn" id="volume-unit-toggle" data-volume-mode="base" title="Volume units: base asset — click for quote asset">${escapeHtml(defaultPairMode === 'inverse' ? assetLabelB : assetLabelA)}</button></div>
547
- ${(((payload.orderBuys?.length || 0) + (payload.orderSells?.length || 0) > 0 || payload.gridBounds?.low != null || payload.gridBounds?.high != null) ? '<div class="indicator"><label><input type="checkbox" id="orders-toggle" checked> Orders</label></div>' : '')}
548
- </div>
549
- </div>
550
- <div class="toolbar-row">
551
- <div class="group">
552
- <div class="indicator">
553
- <label><input type="checkbox" id="ama-toggle"${defaults.amaEnabled ? ' checked' : ''}> AMA</label>
554
- <span class="tag">er</span>
555
- <input type="text" inputmode="numeric" id="ama-er" value="${defaults.amaDefaults.erPeriod}">
556
- <span class="step-stack">
557
- <button type="button" class="step-btn" id="ama-er-inc">▲</button>
558
- <button type="button" class="step-btn" id="ama-er-dec">▼</button>
559
- </span>
560
- <span class="tag">fast</span>
561
- <input type="text" inputmode="decimal" id="ama-fast" value="${defaults.amaDefaults.fastPeriod}">
562
- <span class="step-stack">
563
- <button type="button" class="step-btn" id="ama-fast-inc">▲</button>
564
- <button type="button" class="step-btn" id="ama-fast-dec">▼</button>
565
- </span>
566
- <span class="tag">slow</span>
567
- <input type="text" inputmode="decimal" id="ama-slow" value="${defaults.amaDefaults.slowPeriod}">
568
- <span class="step-stack">
569
- <button type="button" class="step-btn" id="ama-slow-inc">▲</button>
570
- <button type="button" class="step-btn" id="ama-slow-dec">▼</button>
571
- </span>
572
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA1" title="AMA1 (slow 62.1)">1</button>
573
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA2" title="AMA2 (slow 72.0)">2</button>
574
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA3" title="AMA3 (slow 83.6)">3</button>
575
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA4" title="AMA4 (slow 96.9)">4</button>
576
- </div>
577
- <div class="indicator" title="Range min/max built only from the live AMA price (red above, green below); Scale sizes it by AMA slope like the grid build">
578
- <label><input type="checkbox" id="range-toggle"${defaults.rangeEnabled ? ' checked' : ''}> Range</label>
579
- <label title="Range Scaling: size the band by AMA slope like the grid build (trend side widens, opposite tightens) and fit the price axis to it"><input type="checkbox" id="range-scale-toggle"${defaults.rangeScaleEnabled ? ' checked' : ''}> Scale</label>
580
- <span id="range-grid-wrap" style="display:inline" title="x-range around AMA (1.2x–2.0x)">
581
- <input type="range" id="range-span" min="1.2" max="2" step="0.05" value="${defaults.rangeSpan.toFixed(2)}" style="width:90px;vertical-align:middle">
582
- <span id="range-span-val" style="font-size:11px;color:#8b949e;width:40px;display:inline-block;text-align:right">${defaults.rangeSpan.toFixed(2)}x</span>
583
- </span>
584
- </div>
585
- <div class="indicator">
586
- <label title="Init Offset"><input type="checkbox" id="ama-init-offset-toggle"> Offset</label>
587
- <input type="range" id="ama-init-offset" min="-50" max="50" value="0" step="1" style="width:90px;vertical-align:middle" disabled>
588
- <span id="ama-init-offset-val" style="font-size:11px;color:#8b949e;width:32px;display:inline-block;text-align:right">0%</span>
589
- </div>
590
- </div>
591
- </div>
592
- </div>
593
- </div>
594
- <div id="chart-shell">
595
- <div id="legend">
596
- <div class="legend-line">
597
- <span class="legend-item"><span class="legend-label">Time</span> <span class="legend-value" id="legend-time">-</span></span>
598
- <span class="legend-item"><span class="legend-label">C</span> <span class="legend-value" id="legend-close">-</span></span>
599
- <span class="legend-item"><span class="legend-label">Delta</span> <span class="legend-value" id="legend-delta">-</span></span>
600
- <span class="legend-item"><span class="legend-label">Vol</span> <span class="legend-value" id="legend-volume" title="${payload.volumeIsCount ? 'Volume: feed publish count per bucket' : 'Volume units — click to switch base/quote'}" style="cursor:${payload.volumeIsCount ? 'default' : 'pointer'}">-</span></span>
601
- </div>
602
- <div class="legend-line">
603
- <span class="legend-item"><span class="legend-dot" style="background:#f59e0b"></span><span class="legend-label">SMA</span> <span class="legend-value" id="legend-sma">-</span></span>
604
- <span class="legend-item"><span class="legend-dot" style="background:#93c5fd"></span><span class="legend-label">VWMA</span> <span class="legend-value" id="legend-vwap">-</span></span>
605
- <span class="legend-item"><span class="legend-dot" style="background:#22c55e"></span><span class="legend-label">AMA Init</span> <span class="legend-value" id="legend-sma-init">-</span></span>
606
- <span class="legend-item"><span class="legend-dot" style="background:#2dd4bf"></span><span class="legend-label">AMA</span> <span class="legend-value" id="legend-ama">-</span></span>
607
- </div>
608
- </div>
609
- <div id="price-chart" title="Wheel: zoom time (out = empty space around data) · Shift+wheel: zoom price · Drag: pan time + price (sets manual price scale) · Wheel/drag on price axis: zoom price · Drag on time axis: zoom time · Double-click price axis: autofit"></div>
610
- <div id="volume-chart"></div>
611
- </div>
612
- </div>
613
-
614
- <script id="payload" type="application/json">${serializeJsonForScript(payload)}</script>
615
- <script>
616
- (function () {
617
- const payload = JSON.parse(document.getElementById('payload').textContent);
618
- const priceEl = document.getElementById('price-chart');
619
- const volumeEl = document.getElementById('volume-chart');
620
- const baseCandles = Array.isArray(payload.candles) ? payload.candles.slice() : [];
621
- const baseCloseValues = baseCandles.map((c) => c.close);
622
- const timeframes = Array.isArray(payload.timeframes) ? payload.timeframes.slice() : [];
623
- const timeframeMap = new Map(timeframes.map((item) => [item.label, item]));
624
- const STORAGE_KEY = typeof payload.storageKey === 'string' && payload.storageKey.length > 0
625
- ? payload.storageKey
626
- : 'dexbot2-tradingview-uplot-v3:default';
627
- const SYNC_KEY = typeof payload.syncKey === 'string' && payload.syncKey.length > 0
628
- ? payload.syncKey
629
- : 'dexbot2-tradingview-sync';
630
-
631
- const state = loadState();
632
- let currentTimeframe = state.timeframe || payload.defaultTimeframe || '1h';
633
- let currentSmaEnabled = state.smaEnabled ?? !!payload.smaEnabled;
634
- let currentSmaPeriod = Number.isFinite(state.smaPeriod) ? state.smaPeriod : Number(payload.smaPeriod || 500);
635
- let currentAmaEnabled = state.amaEnabled ?? !!payload.amaEnabled;
636
- let currentAmaErPeriod = Number.isFinite(state.amaErPeriod)
637
- ? Number(state.amaErPeriod)
638
- : Number(payload.amaDefaults?.erPeriod || ${MARKET_ADAPTER.AMAS.AMA3.erPeriod});
639
- let currentAmaFastPeriod = Number.isFinite(state.amaFastPeriod)
640
- ? Number(state.amaFastPeriod)
641
- : Number(payload.amaDefaults?.fastPeriod || ${MARKET_ADAPTER.AMAS.AMA3.fastPeriod});
642
- let currentAmaSlowPeriod = Number.isFinite(state.amaSlowPeriod)
643
- ? Number(state.amaSlowPeriod)
644
- : Number(payload.amaDefaults?.slowPeriod || ${MARKET_ADAPTER.AMAS.AMA3.slowPeriod});
645
- let currentVwapEnabled = state.vwapEnabled ?? !!payload.vwapEnabled;
646
- let currentVwapBars = Number.isFinite(state.vwapBars) ? state.vwapBars : Number(payload.vwapBars || 500);
647
- let currentRangeEnabled = state.rangeEnabled ?? !!payload.rangeEnabled;
648
- let currentRangeScaleEnabled = state.rangeScaleEnabled ?? !!payload.rangeScaleEnabled;
649
- let currentRangeWidthPct = Number.isFinite(state.rangeWidthPct) && Number(state.rangeWidthPct) > 0
650
- ? Number(state.rangeWidthPct)
651
- : (Number.isFinite(Number(payload.rangeWidthPct)) && Number(payload.rangeWidthPct) > 0 ? Number(payload.rangeWidthPct) : 2);
652
- let currentRangeSpan = Number.isFinite(state.rangeSpan) && Number(state.rangeSpan) > 0
653
- ? Math.min(2, Math.max(1.2, Number(state.rangeSpan)))
654
- : (Number.isFinite(Number(payload.rangeSpan)) && Number(payload.rangeSpan) > 0 ? Math.min(2, Math.max(1.2, Number(payload.rangeSpan))) : 1.55);
655
- let currentOrdersVisible = state.ordersVisible ?? true;
656
- let currentVolumeVisible = state.volumeVisible ?? true;
657
- let currentVolumeMode = state.volumeMode === 'quote' ? 'quote' : 'base';
658
- // Static per generation: the overlay (levels, reserve/ceiling lines,
659
- // spread label) exists only when order data was embedded.
660
- // --no-orders or a missing orders file therefore removes the whole
661
- // overlay, including the reserve/ceiling lines.
662
- const hasOrders = ((payload.orderBuys?.length || 0) + (payload.orderSells?.length || 0)) > 0;
663
- // Bounds-only grids (virtual slots, no live levels yet) still show
664
- // the reserve/ceiling lines; levels/spread/panel rows need live data.
665
- const hasBounds = payload.gridBounds?.low != null || payload.gridBounds?.high != null;
666
- let currentAmaInitOffsetEnabled = false;
667
- let currentAmaInitOffset = Number.isFinite(state.amaInitOffset) ? state.amaInitOffset : 0;
668
- let currentPriceScale = state.priceScale || payload.priceScale || 'log';
669
- let currentPairMode = state.pairMode === 'inverse' ? 'inverse' : (payload.defaultPairMode === 'inverse' ? 'inverse' : 'normal');
670
- let currentCandles = [];
671
- let currentSeriesState = null;
672
- let currentSeriesCandles = baseCandles;
673
- let currentSeriesCloseValues = baseCloseValues;
674
- let currentOpen = [];
675
- let currentHigh = [];
676
- let currentLow = [];
677
- let currentClose = [];
678
- let currentDisplayCandles = [];
679
- let currentPriceData = [];
680
- let currentVolumeData = [];
681
- let currentSma = [];
682
- let currentAma = [];
683
- let currentVwap = [];
684
- let currentSmaInit = [];
685
- let currentSmaInitOff = [];
686
- let currentAmaOff = [];
687
- let currentRangeUpper = [];
688
- let currentRangeLower = [];
689
- let priceChart = null;
690
- let volumeChart = null;
691
- let lastRenderedPriceScale = null;
692
- let charts = [];
693
- let chartEventsBound = false;
694
- let manualYRange = null;
695
- let lastCandleKey = null;
696
- let pendingRange = null;
697
- let pendingRangeRaf = 0;
698
- let rangePanelRaf = 0;
699
- let yRefitRaf = 0;
700
- let xMin = 0;
701
- let xMax = 0;
702
- let smaWorker = null;
703
- let smaWorkerJob = null;
704
- let smaWorkerStartRaf = 0;
705
- let smaWorkerPaintRaf = 0;
706
- let smaWorkerSeq = 0;
707
- const aggregateCache = new Map();
708
- const smaCache = new Map();
709
- const amaCache = new Map();
710
- const vwapCache = new Map();
711
- const seriesCache = new Map();
712
-
713
- ${UPLOT_SHARED_SCRIPT}
714
-
715
- // TradingView-exporter interaction overrides (PR #3 / #11 feature):
716
- // redeclare after UPLOT_SHARED_SCRIPT so these hoisted declarations win
717
- // for this page only, without mutating the shared stack used by other charts.
718
- function bindWheelZoom(chart) {
719
- chart.root.addEventListener('wheel', (e) => {
720
- if (e.ctrlKey || e.metaKey || e.altKey) return;
721
- e.preventDefault();
722
- const rect = chart.root.getBoundingClientRect();
723
- const pxRatio = chart.pxRatio || 1;
724
- const bboxLeft = chart.bbox ? chart.bbox.left / pxRatio : 0;
725
- const bboxTop = chart.bbox ? chart.bbox.top / pxRatio : 0;
726
- // Shift+wheel scales price (cursor-anchored) anywhere over the
727
- // price pane — same as wheeling over the price axis. Volume has
728
- // no manual Y lock, so it keeps the timeframe zoom.
729
- if (chart === priceChart && (e.shiftKey || inYAxisZone(chart, e.clientX))) {
730
- const centerY = chart.posToVal(e.clientY - rect.top - bboxTop, 'y');
731
- const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX;
732
- zoomYAt(chart, centerY, delta < 0 ? 0.91 : 1.10);
733
- return;
734
- }
735
- e.stopPropagation();
736
- const left = e.clientX - rect.left - bboxLeft;
737
- const center = chart.posToVal(left, 'x');
738
- const s = chart.scales.x || {};
739
- const currMin = Number.isFinite(s.min) ? s.min : xMin;
740
- const currMax = Number.isFinite(s.max) ? s.max : xMax;
741
- const span = currMax - currMin;
742
- if (!Number.isFinite(span) || span <= 0) return;
743
- const factor = e.deltaY < 0 ? 0.85 : 1.15;
744
- // Uloszoomaus datan reunojen yli: kokonaisnakyyma enintaan 2.5x datan pituus
745
- const fullSpan = Math.max(1, xMax - xMin);
746
- const nextSpan = Math.max(1, Math.min(fullSpan * 2.5, span * factor));
747
- const ratio = (center - currMin) / span;
748
- syncXRange(center - nextSpan * ratio, center - nextSpan * ratio + nextSpan);
749
- }, { passive: false });
750
- }
751
- function clampRange(min, max) {
752
- if (!Number.isFinite(xMin) || !Number.isFinite(xMax) || xMax <= xMin) return null;
753
- if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) return null;
754
- // Allow empty space on both sides of the data (TradingView-style):
755
- // enintaan 75 % datan pituudesta reunapuskurina kummallekin puolelle.
756
- // Span-locked: pans slide the window and never squash it — only a
757
- // deliberate over-wide zoom-out is centered down to the limit.
758
- // Plot drags therefore move but never scale; scaling lives on
759
- // the axis gutters alone.
760
- const dataSpan = Math.max(1, xMax - xMin);
761
- const maxPad = dataSpan * 0.75;
762
- const lo = xMin - maxPad;
763
- const hi = xMax + maxPad;
764
- const span = max - min;
765
- if (span > hi - lo) {
766
- const center = (min + max) / 2;
767
- const half = (hi - lo) / 2;
768
- return { min: center - half, max: center + half };
769
- }
770
- let nMin = min;
771
- if (nMin < lo) nMin = lo;
772
- if (nMin + span > hi) nMin = hi - span;
773
- return { min: nMin, max: nMin + span };
774
- }
775
- function syncXRange(min, max) {
776
- pendingRange = clampRange(min, max);
777
- if (pendingRangeRaf) return;
778
- pendingRangeRaf = requestAnimationFrame(() => {
779
- const next = pendingRange;
780
- pendingRange = null;
781
- pendingRangeRaf = 0;
782
- if (!next || charts.length === 0) return;
783
- charts.forEach((chart) => chart.batch(() => chart.setScale('x', next)));
784
- });
785
- }
786
- function bindPan(chart) {
787
- let dragging = false;
788
- let startClientX = 0;
789
- let startClientY = 0;
790
- let startMin = 0;
791
- let startMax = 0;
792
- let startYRange = null;
793
- let startBboxLeft = 0;
794
- let startBboxTop = 0;
795
- let panRaf = 0;
796
- let pendingPan = null;
797
- const applyPendingPan = () => {
798
- panRaf = 0;
799
- const p = pendingPan;
800
- pendingPan = null;
801
- if (!dragging || !p) return;
802
- // Plot drag pans time and price (TradingView-style): the price
803
- // move sets a manual Y range; double-click the price axis to
804
- // return to autofit. Axis gutters never pan — they scale.
805
- if (chart === priceChart && startYRange && Number.isFinite(p.clientY)) {
806
- // Plot-relative coords: subtract the axis gutter offset
807
- // (bbox) like bindWheelZoom. On linear scales the offset
808
- // cancels in subtraction, but on log scale the ratio
809
- // corrupts and vertical drag dies without it.
810
- const vStart = chart.posToVal(p.startY - p.rectTop - p.bboxTop, 'y');
811
- const vCur = chart.posToVal(p.clientY - p.rectTop - p.bboxTop, 'y');
812
- if (Number.isFinite(vStart) && Number.isFinite(vCur) && vCur !== vStart) {
813
- // Rigid move only: the span is locked by construction so a
814
- // plot drag can never rescale — Y scaling happens solely
815
- // on the price-axis gutter (wheel/drag there).
816
- if (currentPriceScale === 'log') {
817
- const ratio = Math.max(1e-12, vStart) / Math.max(1e-12, vCur);
818
- const spanRatio = startYRange.max / startYRange.min;
819
- if (Number.isFinite(ratio) && ratio > 0 && Number.isFinite(spanRatio) && spanRatio > 0) {
820
- const nextMin = startYRange.min * ratio;
821
- applyYRange(chart, nextMin, nextMin * spanRatio);
822
- }
823
- } else {
824
- const dy = vStart - vCur;
825
- const span = startYRange.max - startYRange.min;
826
- if (Number.isFinite(dy) && Number.isFinite(span) && span > 0) {
827
- const nextMin = startYRange.min + dy;
828
- applyYRange(chart, nextMin, nextMin + span);
829
- }
830
- }
831
- }
832
- }
833
- const delta = chart.posToVal(p.clientX - p.rectLeft - p.bboxLeft, 'x') - chart.posToVal(p.startX - p.rectLeft - p.bboxLeft, 'x');
834
- syncXRange(startMin - delta, startMax - delta);
835
- };
836
- const onMove = (e) => {
837
- if (!dragging) return;
838
- e.preventDefault();
839
- const rect = chart.root.getBoundingClientRect();
840
- pendingPan = {
841
- clientX: e.clientX, clientY: e.clientY,
842
- startX: startClientX, startY: startClientY,
843
- rectLeft: rect.left, rectTop: rect.top,
844
- bboxLeft: startBboxLeft, bboxTop: startBboxTop,
845
- };
846
- if (!panRaf) panRaf = requestAnimationFrame(applyPendingPan);
847
- };
848
- const endDrag = () => {
849
- if (!dragging) return;
850
- dragging = false;
851
- startYRange = null;
852
- pendingPan = null;
853
- if (panRaf) { cancelAnimationFrame(panRaf); panRaf = 0; }
854
- document.body.style.cursor = '';
855
- window.removeEventListener('mousemove', onMove);
856
- window.removeEventListener('mouseup', endDrag);
857
- };
858
- chart.root.addEventListener('mousedown', (e) => {
859
- if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;
860
- const rect = chart.root.getBoundingClientRect();
861
- if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
862
- if (chart === priceChart && inYAxisZone(chart, e.clientX)) return;
863
- if (inXAxisZone(chart, e.clientY)) return;
864
- e.preventDefault();
865
- e.stopPropagation();
866
- dragging = true;
867
- startClientX = e.clientX;
868
- startClientY = e.clientY;
869
- const startPxRatio = chart.pxRatio || 1;
870
- startBboxLeft = chart.bbox ? chart.bbox.left / startPxRatio : 0;
871
- startBboxTop = chart.bbox ? chart.bbox.top / startPxRatio : 0;
872
- const s = chart.scales.x || {};
873
- startMin = Number.isFinite(s.min) ? s.min : currentCandles[0].time;
874
- startMax = Number.isFinite(s.max) ? s.max : currentCandles[currentCandles.length - 1].time;
875
- if (chart === priceChart) startYRange = currentYRange(chart);
876
- document.body.style.cursor = 'grabbing';
877
- window.addEventListener('mousemove', onMove);
878
- window.addEventListener('mouseup', endDrag, { once: true });
879
- });
880
- }
881
- function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
882
- // Significant-digit price formatting (4 "active" digits), matching the
883
- // DEXBot order-price style (formatCurrency).
884
- // Very small values get SI micro-suffixes (m/µ/n/p/...); large values
885
- // get comma grouping. Examples: 34.94 -> "34.94", 119.98 -> "120.0",
886
- // 3014.9 -> "3,015", 0.00567 -> "5.670m".
887
- function fmtPrice(v) {
888
- if (v == null || !Number.isFinite(v)) return '-';
889
- const num = Number(v);
890
- if (num === 0) return '0';
891
- const abs = Math.abs(num);
892
- if (abs < 0.1) {
893
- if (abs >= 0.001) return fmtPrice(num * 1000) + 'm';
894
- if (abs >= 0.000001) return fmtPrice(num * 1e6) + 'µ';
895
- if (abs >= 1e-9) return fmtPrice(num * 1e9) + 'n';
896
- if (abs >= 1e-12) return fmtPrice(num * 1e12) + 'p';
897
- if (abs >= 1e-15) return fmtPrice(num * 1e15) + 'f';
898
- if (abs >= 1e-18) return fmtPrice(num * 1e18) + 'a';
899
- return num.toFixed(6);
900
- }
901
- const digits = 4;
902
- let intDigits = Math.floor(Math.log10(abs)) + 1;
903
- if (abs < 1) intDigits = 1;
904
- const formatted = intDigits >= digits ? String(Math.round(num)) : num.toFixed(digits - intDigits);
905
- return intDigits >= 4 ? formatted.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : formatted;
906
- }
907
- function fmtPriceAxis(vals) {
908
- if (!Array.isArray(vals) || vals.length === 0) return [];
909
- return vals.map((v) => (v == null || !Number.isFinite(v)) ? '' : fmtPrice(v));
910
- }
911
- function fmtPriceLabel(v) {
912
- if (v == null || !Number.isFinite(v)) return '-';
913
- return fmtPrice(v);
914
- }
915
- function logAxisSplits(self, axisIdx, scaleMin, scaleMax, foundIncr, foundSpace) {
916
- if (!Number.isFinite(scaleMin) || !Number.isFinite(scaleMax) || scaleMin <= 0 || scaleMax <= 0) return [];
917
- let h = 600;
918
- if (self && self.bbox && Number.isFinite(self.bbox.height)) h = self.bbox.height / (self.pxRatio || 1);
919
- else if (self && self.over && self.over.clientHeight) h = self.over.clientHeight;
920
- const target = Math.max(8, Math.min(16, Math.floor(h / 30)));
921
- const lmin = Math.log10(scaleMin);
922
- const lmax = Math.log10(scaleMax);
923
- const out = [];
924
- for (let i = 0; i <= target; i++) {
925
- out.push(Math.pow(10, lmin + (lmax - lmin) * (i / target)));
926
- }
927
- return out;
928
- }
929
- // Significant-digit volume formatting (4 "active" digits) with K/M/B/T
930
- // suffixes, matching the price-axis style. Examples: 1234567 -> "1235K",
931
- // 1234567890 -> "1.235B".
932
- function fmtVolume(v) {
933
- if (v == null || !Number.isFinite(v)) return '-';
934
- const num = Number(v);
935
- if (num === 0) return '0';
936
- const abs = Math.abs(num);
937
- const units = [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'K']];
938
- for (const [factor, suffix] of units) {
939
- if (abs >= factor) {
940
- const scaled = num / factor;
941
- const a = Math.abs(scaled);
942
- let intDigits = Math.floor(Math.log10(a)) + 1;
943
- if (a < 1) intDigits = 1;
944
- const digits = 4;
945
- const formatted = intDigits >= digits ? String(Math.round(scaled)) : scaled.toFixed(digits - intDigits);
946
- return formatted + suffix;
947
- }
948
- }
949
- let intDigits = Math.floor(Math.log10(abs)) + 1;
950
- if (abs < 1) intDigits = 1;
951
- const digits = 4;
952
- return intDigits >= digits ? String(Math.round(num)) : num.toFixed(digits - intDigits);
953
- }
954
- function candleDirection(open, close) {
955
- if (close > open) return 'up';
956
- if (close < open) return 'down';
957
- return 'flat';
958
- }
959
- function fmtTime(ts) {
960
- if (!Number.isFinite(ts)) return '-';
961
- const d = new Date(ts * 1000);
962
- return d.toLocaleString(undefined, { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
963
- }
964
- function pad2(n) {
965
- return String(n).padStart(2, '0');
966
- }
967
- function formatTimeLabel(tsSec, spanSec) {
968
- const d = new Date(tsSec * 1000);
969
- if (!Number.isFinite(spanSec)) spanSec = 0;
970
- if (spanSec >= 365 * 24 * 3600 * 2) {
971
- return String(d.getUTCFullYear());
972
- }
973
- if (spanSec >= 90 * 24 * 3600) {
974
- return d.toLocaleString(undefined, { month: 'short', year: 'numeric', timeZone: 'UTC' });
975
- }
976
- if (spanSec >= 14 * 24 * 3600) {
977
- return d.toLocaleString(undefined, { month: 'short', day: '2-digit', timeZone: 'UTC' });
978
- }
979
- return d.toLocaleString(undefined, { month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' });
980
- }
981
- function makeTimeAxis(showLabels) {
982
- return {
983
- show: true,
984
- size: showLabels ? 24 : 14,
985
- stroke: '#ffffff',
986
- grid: { stroke: '#1c2128' },
987
- ticks: { stroke: '#30363d', width: 1 },
988
- font: '11px Segoe UI, sans-serif',
989
- values: showLabels ? (u, vals) => {
990
- if (String(currentTimeframe) === '1M') {
991
- return vals.map((ts) => new Date(ts * 1000).toLocaleString(undefined, { month: 'short', year: 'numeric', timeZone: 'UTC' }));
992
- }
993
- const xScale = u.scales.x || {};
994
- const spanSec = Number.isFinite(xScale.min) && Number.isFinite(xScale.max)
995
- ? Math.max(0, xScale.max - xScale.min)
996
- : 0;
997
- return vals.map((ts) => formatTimeLabel(ts, spanSec));
998
- } : () => [],
999
- };
1000
- }
1001
- function loadState() {
1002
- try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}'); } catch (e) { return {}; }
1003
- }
1004
- function saveState() {
1005
- try {
1006
- localStorage.setItem(STORAGE_KEY, JSON.stringify({
1007
- timeframe: currentTimeframe,
1008
- smaEnabled: currentSmaEnabled,
1009
- smaPeriod: currentSmaPeriod,
1010
- amaEnabled: currentAmaEnabled,
1011
- amaErPeriod: currentAmaErPeriod,
1012
- amaFastPeriod: currentAmaFastPeriod,
1013
- amaSlowPeriod: currentAmaSlowPeriod,
1014
- vwapEnabled: currentVwapEnabled,
1015
- vwapBars: currentVwapBars,
1016
- rangeEnabled: currentRangeEnabled,
1017
- rangeScaleEnabled: currentRangeScaleEnabled,
1018
- rangeWidthPct: currentRangeWidthPct,
1019
- rangeSpan: currentRangeSpan,
1020
- ordersVisible: currentOrdersVisible,
1021
- volumeVisible: currentVolumeVisible,
1022
- volumeMode: currentVolumeMode,
1023
- amaInitOffset: currentAmaInitOffset,
1024
- priceScale: currentPriceScale,
1025
- pairMode: currentPairMode,
1026
- }));
1027
- } catch (e) {}
1028
- }
1029
- function normalizePairMode(mode) {
1030
- return String(mode).toLowerCase() === 'inverse' ? 'inverse' : 'normal';
1031
- }
1032
- function getPairLabel(mode = currentPairMode) {
1033
- return normalizePairMode(mode) === 'inverse'
1034
- ? (payload.pairLabelInverse || (payload.assetLabelB + '/' + payload.assetLabelA))
1035
- : (payload.pairLabelNormal || (payload.assetLabelA + '/' + payload.assetLabelB));
1036
- }
1037
- // Volume units: base = displayed pair's base asset (TradingView
1038
- // standard, VWMA-correct), quote = base * display close (per-candle
1039
- // approximation of true quote volume). Persisted per chart in
1040
- // localStorage like the AMA settings (volumeMode).
1041
- function getVolumeSymbols() {
1042
- const inverse = normalizePairMode(currentPairMode) === 'inverse';
1043
- return {
1044
- base: inverse ? payload.assetLabelB : payload.assetLabelA,
1045
- quote: inverse ? payload.assetLabelA : payload.assetLabelB,
1046
- };
1047
- }
1048
- function getVolumeUnit() {
1049
- if (payload.volumeIsCount) return { mode: 'count', symbol: 'feeds' };
1050
- const syms = getVolumeSymbols();
1051
- return currentVolumeMode === 'quote'
1052
- ? { mode: 'quote', symbol: syms.quote }
1053
- : { mode: 'base', symbol: syms.base };
1054
- }
1055
- function getDisplayVolume(c) {
1056
- const v = Number(c?.volume);
1057
- if (!Number.isFinite(v)) return NaN;
1058
- if (payload.volumeIsCount) return v;
1059
- if (currentVolumeMode === 'quote') {
1060
- const p = Number(c?.close);
1061
- return Number.isFinite(p) && p > 0 ? v * p : NaN;
1062
- }
1063
- return v;
1064
- }
1065
- function fmtVolumeWithSym(v) {
1066
- const s = fmtVolume(v);
1067
- if (s == null || s === '-') return '-';
1068
- const u = getVolumeUnit();
1069
- return u.symbol ? s + ' ' + u.symbol : s;
1070
- }
1071
- function setActiveVolumeUnit() {
1072
- const btn = document.getElementById('volume-unit-toggle');
1073
- if (!btn) return;
1074
- const u = getVolumeUnit();
1075
- btn.dataset.volumeMode = u.mode;
1076
- btn.textContent = u.symbol || u.mode;
1077
- btn.title = payload.volumeIsCount
1078
- ? 'Volume: feed publish count per bucket'
1079
- : (u.mode === 'quote'
1080
- ? 'Volume units: quote asset (' + u.symbol + ') — click for base asset'
1081
- : 'Volume units: base asset (' + u.symbol + ') — click for quote asset');
1082
- btn.disabled = !!payload.volumeIsCount;
1083
- btn.style.opacity = payload.volumeIsCount ? '0.45' : '';
1084
- btn.style.cursor = payload.volumeIsCount ? 'not-allowed' : 'pointer';
1085
- const lv = document.getElementById('legend-volume');
1086
- if (lv) {
1087
- lv.style.cursor = payload.volumeIsCount ? 'default' : 'pointer';
1088
- lv.title = payload.volumeIsCount
1089
- ? 'Volume: feed publish count per bucket'
1090
- : 'Volume units — click to switch base/quote';
1091
- }
1092
- const vp = document.getElementById('vol-panel');
1093
- if (vp) {
1094
- vp.style.cursor = payload.volumeIsCount ? 'default' : 'pointer';
1095
- vp.title = payload.volumeIsCount
1096
- ? 'Volume: feed publish count per bucket'
1097
- : 'Volume units — click to switch base/quote';
1098
- }
1099
- }
1100
- function toggleVolumeUnit() {
1101
- if (payload.volumeIsCount) return;
1102
- currentVolumeMode = currentVolumeMode === 'quote' ? 'base' : 'quote';
1103
- setActiveVolumeUnit();
1104
- rerender(true);
1105
- }
1106
- function refreshSubtitle() {
1107
- const subtitleEl = document.getElementById('subtitle');
1108
- if (!subtitleEl) return;
1109
- subtitleEl.textContent = payload.poolLabel + ' · ' + getPairLabel() + ' · ' + payload.intervalLabel + ' base · indicators from 1h · volume · uPlot';
1110
- }
1111
- function snapInitOffset(value) {
1112
- const next = Math.round(Number(value) || 0);
1113
- return Math.abs(next) <= 2 ? 0 : next;
1114
- }
1115
- function setActivePairMode(mode) {
1116
- const label = normalizePairMode(mode);
1117
- const btn = document.getElementById('pair-toggle');
1118
- if (!btn) return;
1119
- btn.dataset.pairMode = label;
1120
- btn.classList.toggle('is-inverse', label === 'inverse');
1121
- btn.title = label === 'inverse' ? 'Swap to A/B' : 'Swap to B/A';
1122
- btn.setAttribute('aria-label', label === 'inverse' ? 'Swap to A/B' : 'Swap to B/A');
1123
- }
1124
- function invertCandle(candle) {
1125
- const open = Number(candle?.open);
1126
- const high = Number(candle?.high);
1127
- const low = Number(candle?.low);
1128
- const close = Number(candle?.close);
1129
- if (![open, high, low, close].every(Number.isFinite) || open <= 0 || high <= 0 || low <= 0 || close <= 0) return null;
1130
- const volume = Number(candle?.volume);
1131
- return {
1132
- time: candle.time,
1133
- open: 1 / open,
1134
- high: 1 / low,
1135
- low: 1 / high,
1136
- close: 1 / close,
1137
- // Convert base-asset volume into the inverse pair's base units approximately.
1138
- volume: Number.isFinite(volume) ? volume * close : 0,
1139
- };
1140
- }
1141
- function getSeriesState(mode = currentPairMode) {
1142
- const key = normalizePairMode(mode);
1143
- if (seriesCache.has(key)) return seriesCache.get(key);
1144
- const candles = key === 'inverse'
1145
- ? baseCandles.map(invertCandle).filter(Boolean)
1146
- : baseCandles.slice();
1147
- const state = {
1148
- candles,
1149
- closeValues: candles.map((c) => c.close),
1150
- };
1151
- seriesCache.set(key, state);
1152
- return state;
1153
- }
1154
- function aggregateCandles(rows, seconds, label) {
1155
- const monthly = String(label || '') === '1M';
1156
- const bucketSec = Math.max(1, Math.round(seconds || 3600));
1157
- const cacheKey = currentPairMode + '|' + (monthly ? '1M' : String(bucketSec));
1158
- if (aggregateCache.has(cacheKey)) return aggregateCache.get(cacheKey);
1159
- const out = [];
1160
- const idxs = [];
1161
- let cur = null;
1162
- let curBucket = null;
1163
- let curIdx = -1;
1164
- const finishBucket = (bucket) => {
1165
- if (!bucket) return;
1166
- // Feed volume is a publication rate, not trade quantity. Keep
1167
- // it comparable across 1h/week/month views instead of turning
1168
- // a monthly candle into a sum such as 388 publishes.
1169
- if (payload.volumeIsCount && bucket.barCount > 0) {
1170
- bucket.volume /= bucket.barCount;
1171
- }
1172
- delete bucket.barCount;
1173
- out.push(bucket);
1174
- };
1175
- for (let i = 0; i < rows.length; i++) {
1176
- const row = rows[i];
1177
- const ts = Number(row.time);
1178
- if (!Number.isFinite(ts)) continue;
1179
- let bucket;
1180
- if (monthly) {
1181
- const d = new Date(ts * 1000);
1182
- bucket = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1) / 1000;
1183
- } else {
1184
- bucket = Math.floor(ts / bucketSec) * bucketSec;
1185
- }
1186
- if (!cur || bucket !== curBucket) {
1187
- if (cur) {
1188
- finishBucket(cur);
1189
- idxs.push(curIdx);
1190
- }
1191
- curBucket = bucket;
1192
- curIdx = i;
1193
- cur = {
1194
- time: bucket,
1195
- open: row.open,
1196
- high: row.high,
1197
- low: row.low,
1198
- close: row.close,
1199
- volume: row.volume || 0,
1200
- barCount: 1,
1201
- };
1202
- } else {
1203
- cur.high = Math.max(cur.high, row.high);
1204
- cur.low = Math.min(cur.low, row.low);
1205
- cur.close = row.close;
1206
- cur.volume += row.volume || 0;
1207
- cur.barCount += 1;
1208
- curIdx = i;
1209
- }
1210
- }
1211
- if (cur) {
1212
- finishBucket(cur);
1213
- idxs.push(curIdx);
1214
- }
1215
- const result = { candles: out, idxs };
1216
- aggregateCache.set(cacheKey, result);
1217
- return result;
1218
- }
1219
- function sampleSeriesByIndex(series, idxs) {
1220
- if (!Array.isArray(series) || !Array.isArray(idxs)) return [];
1221
- return idxs.map((idx) => (Number.isFinite(idx) && series[idx] != null ? series[idx] : null));
1222
- }
1223
- function deriveDisplayCandles(candles) {
1224
- if (!Array.isArray(candles) || candles.length === 0) return [];
1225
- return candles.map((c, i) => {
1226
- const prevClose = i > 0 ? candles[i - 1].close : c.close;
1227
- const open = Number.isFinite(prevClose) ? prevClose : c.close;
1228
- const close = c.close;
1229
- return {
1230
- time: c.time,
1231
- open,
1232
- close,
1233
- volume: c.volume,
1234
- };
1235
- });
1236
- }
1237
- function computeSMA(candles, period) {
1238
- const safePeriod = Math.max(1, Math.round(period));
1239
- const cacheKey = currentPairMode + '|' + safePeriod + '|' + candles.length;
1240
- if (smaCache.has(cacheKey)) return smaCache.get(cacheKey);
1241
- const out = [];
1242
- let sum = 0;
1243
- const window = new Array(safePeriod);
1244
- let head = 0;
1245
- let count = 0;
1246
- for (const candle of candles) {
1247
- const price = candle.close;
1248
- if (count < safePeriod) {
1249
- window[count] = price;
1250
- sum += price;
1251
- count++;
1252
- out.push(count === safePeriod ? (sum / safePeriod) : null);
1253
- continue;
1254
- }
1255
- sum -= window[head];
1256
- window[head] = price;
1257
- sum += price;
1258
- head = (head + 1) % safePeriod;
1259
- out.push(sum / safePeriod);
1260
- }
1261
- smaCache.set(cacheKey, out);
1262
- return out;
1263
- }
1264
- function getSmaCacheKey(period) {
1265
- return currentPairMode + '|' + Math.max(1, Math.round(period)) + '|' + currentSeriesCloseValues.length;
1266
- }
1267
- function createSMAWorker() {
1268
- if (typeof Worker === 'undefined' || typeof Blob === 'undefined' || typeof URL === 'undefined') return null;
1269
- const workerSource = [
1270
- 'self.onmessage = function(e) {',
1271
- ' const data = e.data || {};',
1272
- ' const id = data.id;',
1273
- ' const key = data.key;',
1274
- ' const closes = Array.isArray(data.closes) ? data.closes : [];',
1275
- ' const period = Math.max(1, Math.round(Number(data.period) || 1));',
1276
- ' const out = new Array(closes.length);',
1277
- ' const window = new Array(period);',
1278
- ' let sum = 0;',
1279
- ' let head = 0;',
1280
- ' let count = 0;',
1281
- ' for (let i = 0; i < closes.length; i++) {',
1282
- ' const price = Number(closes[i]);',
1283
- ' if (count < period) {',
1284
- ' window[count] = price;',
1285
- ' sum += price;',
1286
- ' count++;',
1287
- ' out[i] = count === period ? (sum / period) : null;',
1288
- ' continue;',
1289
- ' }',
1290
- ' sum -= window[head];',
1291
- ' window[head] = price;',
1292
- ' sum += price;',
1293
- ' head = (head + 1) % period;',
1294
- ' out[i] = sum / period;',
1295
- ' }',
1296
- ' self.postMessage({ id, key, series: out });',
1297
- '};',
1298
- ].join('\\n');
1299
- const blob = new Blob([workerSource], { type: 'text/javascript' });
1300
- const worker = new Worker(URL.createObjectURL(blob));
1301
- worker.onmessage = (e) => {
1302
- const msg = e && e.data ? e.data : {};
1303
- if (!smaWorkerJob || msg.id !== smaWorkerJob.id || msg.key !== smaWorkerJob.key) return;
1304
- smaCache.set(msg.key, Array.isArray(msg.series) ? msg.series : []);
1305
- smaWorkerJob = null;
1306
- if (currentSmaEnabled && msg.key === getSmaCacheKey(currentSmaPeriod)) {
1307
- rerender(false);
1308
- }
1309
- };
1310
- worker.onerror = () => {
1311
- try { worker.terminate(); } catch (e) {}
1312
- smaWorker = null;
1313
- smaWorkerJob = null;
1314
- };
1315
- return worker;
1316
- }
1317
- function clearSMAWorker() {
1318
- if (smaWorkerStartRaf) {
1319
- cancelAnimationFrame(smaWorkerStartRaf);
1320
- smaWorkerStartRaf = 0;
1321
- }
1322
- if (smaWorkerPaintRaf) {
1323
- cancelAnimationFrame(smaWorkerPaintRaf);
1324
- smaWorkerPaintRaf = 0;
1325
- }
1326
- if (!smaWorker) return;
1327
- try { smaWorker.terminate(); } catch (e) {}
1328
- smaWorker = null;
1329
- smaWorkerJob = null;
1330
- }
1331
- function requestSMA(period) {
1332
- const safePeriod = Math.max(1, Math.round(period));
1333
- const key = getSmaCacheKey(safePeriod);
1334
- if (smaCache.has(key)) return;
1335
- if (smaWorkerJob && smaWorkerJob.key === key) return;
1336
- if (smaWorkerJob && smaWorkerJob.key !== key) clearSMAWorker();
1337
- if (!smaWorker) smaWorker = createSMAWorker();
1338
- if (!smaWorker) {
1339
- smaCache.set(key, computeSMA(currentSeriesCandles, safePeriod));
1340
- if (currentSmaEnabled && key === getSmaCacheKey(currentSmaPeriod)) rerender(false);
1341
- return;
1342
- }
1343
- smaWorkerJob = { id: ++smaWorkerSeq, key };
1344
- if (smaWorkerStartRaf) cancelAnimationFrame(smaWorkerStartRaf);
1345
- if (smaWorkerPaintRaf) cancelAnimationFrame(smaWorkerPaintRaf);
1346
- smaWorkerStartRaf = requestAnimationFrame(() => {
1347
- smaWorkerStartRaf = 0;
1348
- smaWorkerPaintRaf = requestAnimationFrame(() => {
1349
- smaWorkerPaintRaf = 0;
1350
- if (!smaWorker || !smaWorkerJob || smaWorkerJob.key !== key || !currentSmaEnabled) return;
1351
- smaWorker.postMessage({
1352
- id: smaWorkerJob.id,
1353
- key,
1354
- period: safePeriod,
1355
- closes: currentSeriesCloseValues,
1356
- });
1357
- });
1358
- });
1359
- }
1360
- function currentAmaConfig() {
1361
- return {
1362
- erPeriod: Math.max(1, Math.round(currentAmaErPeriod)),
1363
- fastPeriod: Math.max(0.1, Number(currentAmaFastPeriod) || 0.1),
1364
- slowPeriod: Math.max(0.1, Number(currentAmaSlowPeriod) || 0.1),
1365
- };
1366
- }
1367
- function computeAMA(candles, cfg, initOffset = 0) {
1368
- const params = cfg || currentAmaConfig();
1369
- const erPeriod = Math.max(1, Math.round(params.erPeriod ?? 10));
1370
- const fastPeriod = Math.max(0.1, Number(params.fastPeriod ?? 2));
1371
- const slowPeriod = Math.max(0.1, Number(params.slowPeriod ?? 30));
1372
- const cacheKey = currentPairMode + '|' + erPeriod + '|' + fastPeriod + '|' + slowPeriod + '|' + candles.length + '|' + initOffset;
1373
- if (amaCache.has(cacheKey)) return amaCache.get(cacheKey);
1374
- const fastSC = 2 / (fastPeriod + 1);
1375
- const slowSC = 2 / (slowPeriod + 1);
1376
- const out = [];
1377
- const windowSize = erPeriod + 1;
1378
- const history = new Array(windowSize);
1379
- let head = 0;
1380
- let len = 0;
1381
- let volatility = 0;
1382
- let prev = null;
1383
- let smaSum = 0;
1384
- for (const candle of candles) {
1385
- const price = candle.close;
1386
- if (len < windowSize) {
1387
- history[(head + len) % windowSize] = price;
1388
- smaSum += price;
1389
- if (len > 0) {
1390
- volatility += Math.abs(price - history[(head + len - 1) % windowSize]);
1391
- }
1392
- len++;
1393
- if (len < windowSize) {
1394
- out.push(null);
1395
- continue;
1396
- }
1397
- prev = initOffset !== 0 ? (smaSum / windowSize) * (1 + initOffset / 100) : smaSum / windowSize;
1398
- out.push(prev);
1399
- continue;
1400
- }
1401
- const oldest = history[head];
1402
- const second = history[(head + 1) % windowSize];
1403
- const last = history[(head + windowSize - 1) % windowSize];
1404
- volatility += Math.abs(price - last) - Math.abs(second - oldest);
1405
- history[head] = price;
1406
- head = (head + 1) % windowSize;
1407
- const first = history[head];
1408
- const direction = Math.abs(price - first);
1409
- const er = volatility === 0 ? 0 : (direction / volatility);
1410
- const smoothing = Math.pow(er * (fastSC - slowSC) + slowSC, 2);
1411
- const ama = prev + smoothing * (price - prev);
1412
- prev = ama;
1413
- out.push(ama);
1414
- }
1415
- amaCache.set(cacheKey, out);
1416
- return out;
1417
- }
1418
- function computeVWMA(candles, bars) {
1419
- const safeBars = Math.max(1, Math.round(bars || 500));
1420
- const cacheKey = currentPairMode + '|' + safeBars + '|' + candles.length;
1421
- if (vwapCache.has(cacheKey)) return vwapCache.get(cacheKey);
1422
- const out = [];
1423
- let cumPV = 0;
1424
- let cumVol = 0;
1425
- const window = new Array(safeBars);
1426
- let head = 0;
1427
- let count = 0;
1428
- for (const candle of candles) {
1429
- const typical = (candle.high + candle.low + candle.close) / 3;
1430
- const volume = Number.isFinite(candle.volume) ? candle.volume : 0;
1431
- cumPV += typical * volume;
1432
- cumVol += volume;
1433
- if (count < safeBars) {
1434
- window[count] = { typical, volume };
1435
- count++;
1436
- } else {
1437
- const old = window[head];
1438
- cumPV -= old.typical * old.volume;
1439
- cumVol -= old.volume;
1440
- window[head] = { typical, volume };
1441
- head = (head + 1) % safeBars;
1442
- }
1443
- out.push(cumVol > 0 ? (cumPV / cumVol) : null);
1444
- }
1445
- vwapCache.set(cacheKey, out);
1446
- return out;
1447
- }
1448
- // Bot-grid range band: min/max derive ONLY from the live AMA price.
1449
- // All math below runs the canonical market_adapter/grid sources,
1450
- // embedded verbatim (not hand-copied): computeAverageAmaSlopePct,
1451
- // computeAmaSlopeClipThreshold, applyAsymmetricBounds (+ metrics/base),
1452
- // applyNarrowingSideGuard, parseRelativeMultiplier. With Range Scaling
1453
- // on, the clipped AMA slope tilts the span-symmetric band like the
1454
- // grid build: trend side widens, opposite side tightens. Painted
1455
- // red [AMA, upper], green [lower, AMA].
1456
- // Never reads candles, pair-display mapping, or axis/zoom state —
1457
- // inversion and timeframe sampling apply to the AMA first.
1458
- ${embedFunctionSources([computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, resolveBaseBounds, computeAsymmetricBoundsMetrics, applyAsymmetricBounds, applyNarrowingSideGuard, parseRelativeMultiplier])}
1459
- function computeRangeBand(baseAma) {
1460
- const n = Array.isArray(baseAma) ? baseAma.length : 0;
1461
- const upper = new Array(n).fill(null);
1462
- const lower = new Array(n).fill(null);
1463
- const trend = new Array(n).fill(0);
1464
- const slopeCfg = payload.rangeSlope || {};
1465
- const gridCfg = payload.grid || null;
1466
- const lookback = Math.max(1, Math.round(Number(slopeCfg.lookbackBars) || 9));
1467
- const maxSlope = Number(slopeCfg.maxSlopePct) > 0 ? Number(slopeCfg.maxSlopePct) : 0.09;
1468
- const neutral = Number(slopeCfg.neutralZonePct) >= 0 ? Number(slopeCfg.neutralZonePct) : 0;
1469
- const maxSlopeOffset = Number(slopeCfg.maxSlopeOffset) > 0 ? Number(slopeCfg.maxSlopeOffset) : 0.5;
1470
- const maxAsym = gridCfg && Number(gridCfg.maxAsymmetryFactor) > 0
1471
- ? Number(gridCfg.maxAsymmetryFactor)
1472
- : (Number(slopeCfg.maxAsymmetryFactor) > 0 ? Number(slopeCfg.maxAsymmetryFactor) : 0.333);
1473
- const inc = gridCfg && Number(gridCfg.incrementPercent) > 0 ? Number(gridCfg.incrementPercent) : null;
1474
- const minSlots = Math.floor(Number(gridCfg && gridCfg.minScaleSlots) > 0 ? Number(gridCfg.minScaleSlots) : (Number(slopeCfg.minScaleSlots) || 0));
1475
- // User x-range span (slider 1.2x–2.0x, default 1.55x): the only
1476
- // width input — symmetric base min = AMA/span, max = AMA*span.
1477
- const span = Math.min(2, Math.max(1.2, Number(currentRangeSpan) > 0 ? Number(currentRangeSpan) : 1.55));
1478
- // Canonical grid pipeline (ama_slope_model): adaptive percentile
1479
- // clip over the AMA history, then offset + trend — the same numbers
1480
- // the live grid build feeds into applyAsymmetricBounds.
1481
- const clipPct = Number(slopeCfg.clipPercentile) >= 0 ? Number(slopeCfg.clipPercentile) : 10;
1482
- const clipEr = Number.isFinite(currentAmaErPeriod) && currentAmaErPeriod > 0
1483
- ? Math.ceil(currentAmaErPeriod)
1484
- : Math.ceil(Number(payload.amaDefaults?.erPeriod) || 781);
1485
- const clipThreshold = computeAmaSlopeClipThreshold(baseAma, clipEr, lookback, clipPct);
1486
- const slopeScaling = !!currentRangeScaleEnabled;
1487
- if (!currentAmaEnabled || n === 0) return { upper, lower, trend };
1488
- for (let i = 0; i < n; i++) {
1489
- const ama = baseAma[i];
1490
- const past = i - lookback >= 0 ? baseAma[i - lookback] : null;
1491
- if (!Number.isFinite(ama) || ama <= 0 || !Number.isFinite(past) || past <= 0) continue;
1492
- const slopePct = computeAverageAmaSlopePct(ama, past, lookback);
1493
- if (slopePct == null || !Number.isFinite(slopePct)) continue;
1494
- const csp = Math.max(-clipThreshold, Math.min(clipThreshold, slopePct));
1495
- const dir = Math.abs(csp) <= neutral ? 0 : (csp > 0 ? 1 : -1);
1496
- // Symmetric base from this bar's AMA and the user span —
1497
- // no chart or config price level.
1498
- let rMin = ama / span;
1499
- let rMax = ama * span;
1500
- if (slopeScaling && dir !== 0) {
1501
- // Canonical tilt: clipped slope offset applied through
1502
- // asymmetric_bounds, then the narrowing-side guard.
1503
- const trendName = dir > 0 ? 'UP' : 'DOWN';
1504
- const slopeOffset = clamp(csp / maxSlope, -1, 1) * maxSlopeOffset;
1505
- const tilt = applyAsymmetricBounds({
1506
- centerPrice: ama,
1507
- minPrice: ama / span,
1508
- maxPrice: ama * span,
1509
- trend: trendName,
1510
- slopeOffset,
1511
- maxSlopeOffset,
1512
- maxAsymmetryFactor: maxAsym,
1513
- });
1514
- const guard = applyNarrowingSideGuard({
1515
- centerPrice: ama,
1516
- minPrice: tilt.resolvedMinPrice,
1517
- maxPrice: tilt.resolvedMaxPrice,
1518
- trend: trendName,
1519
- incrementPercent: inc,
1520
- minScaleSlots: minSlots,
1521
- });
1522
- rMin = guard.minPrice;
1523
- rMax = guard.maxPrice;
1524
- }
1525
- if (!Number.isFinite(rMin) || !Number.isFinite(rMax) || rMin <= 0 || rMax <= rMin) continue;
1526
- upper[i] = rMax;
1527
- lower[i] = rMin;
1528
- trend[i] = dir;
1529
- }
1530
- return { upper, lower, trend };
1531
- }
1532
- function lowerBound(arr, value) {
1533
- let lo = 0;
1534
- let hi = arr.length;
1535
- while (lo < hi) {
1536
- const mid = (lo + hi) >> 1;
1537
- if (arr[mid] < value) lo = mid + 1;
1538
- else hi = mid;
1539
- }
1540
- return lo;
1541
- }
1542
- function visiblePriceRange(u) {
1543
- if (!currentCandles.length) return null;
1544
- const xs = u.data[0];
1545
- const xScale = u.scales.x || {};
1546
- const minX = Number.isFinite(xScale.min) ? xScale.min : xs[0];
1547
- const maxX = Number.isFinite(xScale.max) ? xScale.max : xs[xs.length - 1];
1548
- let start = Math.max(0, lowerBound(xs, minX) - 1);
1549
- let end = Math.min(xs.length, lowerBound(xs, maxX) + 2);
1550
- let min = Infinity;
1551
- let max = -Infinity;
1552
- // Range scaling active: fit the price axis to the full envelope
1553
- // (lower ↔ upper through AMA) instead of the candles, so the
1554
- // switch visibly adjusts the range. Falls through to the candle
1555
- // fit when the band has no finite values in view.
1556
- if (currentRangeEnabled && currentRangeScaleEnabled && currentAmaEnabled) {
1557
- let bmin = Infinity;
1558
- let bmax = -Infinity;
1559
- for (let i = start; i < end; i++) {
1560
- const a = currentAma[i];
1561
- const up = currentRangeUpper[i];
1562
- const lo = currentRangeLower[i];
1563
- if (Number.isFinite(a) && a > 0) { if (a < bmin) bmin = a; if (a > bmax) bmax = a; }
1564
- if (Number.isFinite(up) && up > 0) { if (up < bmin) bmin = up; if (up > bmax) bmax = up; }
1565
- if (Number.isFinite(lo) && lo > 0) { if (lo < bmin) bmin = lo; if (lo > bmax) bmax = lo; }
1566
- }
1567
- if (Number.isFinite(bmin) && Number.isFinite(bmax) && bmin > 0 && bmax > bmin) {
1568
- return [bmin * 0.97, bmax * 1.03];
1569
- }
1570
- }
1571
- for (let i = start; i < end; i++) {
1572
- const lo = currentLow[i];
1573
- const hi = currentHigh[i];
1574
- if (Number.isFinite(lo) && lo > 0 && lo < min) min = lo;
1575
- if (Number.isFinite(hi) && hi > max) max = hi;
1576
- const s = currentSma[i];
1577
- const a = currentAma[i];
1578
- const v = currentVwap[i];
1579
- if (Number.isFinite(s)) { if (s < min) min = s; if (s > max) max = s; }
1580
- if (Number.isFinite(a)) { if (a < min) min = a; if (a > max) max = a; }
1581
- if (Number.isFinite(v)) { if (v < min) min = v; if (v > max) max = v; }
1582
- }
1583
- if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || max <= 0) return null;
1584
- if (min === max) return [min * 0.96, max * 1.04];
1585
- // ~7 % hengitystilaa yla- ja alapuolelle (TradingView-tyyli)
1586
- return [min * 0.93, max * 1.07];
1587
- }
1588
- function visibleVolumeRange(u) {
1589
- if (!currentCandles.length) return null;
1590
- const xs = u.data[0];
1591
- const xScale = u.scales.x || {};
1592
- const minX = Number.isFinite(xScale.min) ? xScale.min : xs[0];
1593
- const maxX = Number.isFinite(xScale.max) ? xScale.max : xs[xs.length - 1];
1594
- let start = Math.max(0, lowerBound(xs, minX) - 1);
1595
- let end = Math.min(xs.length, lowerBound(xs, maxX) + 2);
1596
- let max = 0;
1597
- for (let i = start; i < end; i++) {
1598
- const v = getDisplayVolume(currentCandles[i]);
1599
- if (Number.isFinite(v) && v > max) max = v;
1600
- }
1601
- if (!Number.isFinite(max) || max <= 0) return [0, 1];
1602
- return [0, max * 1.15];
1603
- }
1604
- function setActiveTimeframe(label) {
1605
- document.querySelectorAll('.time-btn').forEach((btn) => btn.classList.toggle('active', btn.dataset.timeframe === label));
1606
- }
1607
- function setActivePriceScale(label) {
1608
- const btn = document.getElementById('scale-toggle');
1609
- if (!btn) return;
1610
- const next = label === 'linear' ? 'linear' : 'log';
1611
- btn.dataset.scale = next;
1612
- btn.classList.toggle('is-linear', next === 'linear');
1613
- btn.textContent = next === 'linear' ? 'Linear' : 'Log';
1614
- btn.title = next === 'linear' ? 'Toggle to log scale' : 'Toggle to linear scale';
1615
- btn.setAttribute('aria-label', next === 'linear' ? 'Toggle to log scale' : 'Toggle to linear scale');
1616
- }
1617
- // AMA presets for the quick buttons (values from constants.ts AMAS).
1618
- const AMA_PRESETS = {
1619
- AMA1: { erPeriod: ${MARKET_ADAPTER.AMAS.AMA1.erPeriod}, fastPeriod: ${MARKET_ADAPTER.AMAS.AMA1.fastPeriod}, slowPeriod: ${MARKET_ADAPTER.AMAS.AMA1.slowPeriod} },
1620
- AMA2: { erPeriod: ${MARKET_ADAPTER.AMAS.AMA2.erPeriod}, fastPeriod: ${MARKET_ADAPTER.AMAS.AMA2.fastPeriod}, slowPeriod: ${MARKET_ADAPTER.AMAS.AMA2.slowPeriod} },
1621
- AMA3: { erPeriod: ${MARKET_ADAPTER.AMAS.AMA3.erPeriod}, fastPeriod: ${MARKET_ADAPTER.AMAS.AMA3.fastPeriod}, slowPeriod: ${MARKET_ADAPTER.AMAS.AMA3.slowPeriod} },
1622
- AMA4: { erPeriod: ${MARKET_ADAPTER.AMAS.AMA4.erPeriod}, fastPeriod: ${MARKET_ADAPTER.AMAS.AMA4.fastPeriod}, slowPeriod: ${MARKET_ADAPTER.AMAS.AMA4.slowPeriod} },
1623
- };
1624
- function markActiveAmaPreset() {
1625
- const cur = { e: Math.round(Number(currentAmaErPeriod)), f: Number(currentAmaFastPeriod), s: Number(currentAmaSlowPeriod) };
1626
- document.querySelectorAll('.ama-preset-btn').forEach((b) => {
1627
- const p = AMA_PRESETS[b.dataset.amaPreset];
1628
- const match = p && Math.round(p.erPeriod) === cur.e && Number(p.fastPeriod) === cur.f && Number(p.slowPeriod) === cur.s;
1629
- b.classList.toggle('active', !!match);
1630
- });
1631
- }
1632
- function applyAmaPreset(key) {
1633
- const p = AMA_PRESETS[key];
1634
- if (!p) return;
1635
- document.getElementById('ama-er').value = String(p.erPeriod);
1636
- document.getElementById('ama-fast').value = String(p.fastPeriod);
1637
- document.getElementById('ama-slow').value = String(p.slowPeriod);
1638
- document.getElementById('ama-toggle').checked = true;
1639
- syncInputs();
1640
- }
1641
- function setIndicatorSeriesVisible(seriesIndex, visible) {
1642
- if (!priceChart) return;
1643
- priceChart.setSeries(seriesIndex, { show: visible }, false, false);
1644
- }
1645
- function syncIndicatorSeriesVisibility() {
1646
- if (!priceChart) return;
1647
- setIndicatorSeriesVisible(5, currentSmaEnabled);
1648
- setIndicatorSeriesVisible(6, currentAmaEnabled);
1649
- setIndicatorSeriesVisible(7, currentVwapEnabled);
1650
- setIndicatorSeriesVisible(8, currentAmaEnabled);
1651
- setIndicatorSeriesVisible(9, currentAmaEnabled && currentAmaInitOffset !== 0);
1652
- setIndicatorSeriesVisible(10, currentAmaEnabled && currentAmaInitOffset !== 0);
1653
- }
1654
- function hideSmaSeriesImmediate() {
1655
- clearSMAWorker();
1656
- currentSma = new Array(currentCandles.length).fill(null);
1657
- if (Array.isArray(currentPriceData) && currentPriceData.length >= 11) {
1658
- currentPriceData[5] = currentSma;
1659
- }
1660
- setIndicatorSeriesVisible(5, false);
1661
- refreshLegend();
1662
- saveState();
1663
- }
1664
- function hideRangeBandImmediate() {
1665
- currentRangeUpper = new Array(currentCandles.length).fill(null);
1666
- currentRangeLower = new Array(currentCandles.length).fill(null);
1667
- // The band is a draw hook with no uPlot series: nothing else
1668
- // repaints on hide, so redraw explicitly (stale pixels otherwise linger).
1669
- if (priceChart && typeof priceChart.redraw === 'function') priceChart.redraw();
1670
- refreshLegend();
1671
- saveState();
1672
- }
1673
- function hideAmaSeriesImmediate() {
1674
- currentAma = new Array(currentCandles.length).fill(null);
1675
- currentAmaOff = new Array(currentCandles.length).fill(null);
1676
- currentSmaInit = new Array(currentCandles.length).fill(null);
1677
- currentSmaInitOff = new Array(currentCandles.length).fill(null);
1678
- currentRangeUpper = new Array(currentCandles.length).fill(null);
1679
- currentRangeLower = new Array(currentCandles.length).fill(null);
1680
- if (Array.isArray(currentPriceData) && currentPriceData.length >= 11) {
1681
- currentPriceData[6] = currentAma;
1682
- currentPriceData[8] = currentSmaInit;
1683
- currentPriceData[9] = currentSmaInitOff;
1684
- currentPriceData[10] = currentAmaOff;
1685
- }
1686
- setIndicatorSeriesVisible(6, false);
1687
- setIndicatorSeriesVisible(8, false);
1688
- setIndicatorSeriesVisible(9, false);
1689
- setIndicatorSeriesVisible(10, false);
1690
- refreshLegend();
1691
- saveState();
1692
- }
1693
- function hideVwapSeriesImmediate() {
1694
- currentVwap = new Array(currentCandles.length).fill(null);
1695
- if (Array.isArray(currentPriceData) && currentPriceData.length >= 11) {
1696
- currentPriceData[7] = currentVwap;
1697
- }
1698
- setIndicatorSeriesVisible(7, false);
1699
- refreshLegend();
1700
- saveState();
1701
- }
1702
- function updateLegend(idx) {
1703
- const c = currentCandles[idx];
1704
- if (!c) return;
1705
- const smaKey = getSmaCacheKey(currentSmaPeriod);
1706
- const smaPending = currentSmaEnabled && smaWorkerJob && smaWorkerJob.key === smaKey && !smaCache.has(smaKey);
1707
- document.getElementById('legend-time').textContent = fmtTime(c.time);
1708
- document.getElementById('legend-close').textContent = fmtPrice(c.close);
1709
- const delta = Number.isFinite(c.open) && Number.isFinite(c.close) ? (c.close - c.open) : null;
1710
- document.getElementById('legend-delta').textContent = Number.isFinite(delta)
1711
- ? ((delta >= 0 ? '+' : '') + fmtPrice(delta))
1712
- : '-';
1713
- document.getElementById('legend-volume').textContent = fmtVolumeWithSym(getDisplayVolume(c));
1714
- document.getElementById('legend-sma').textContent = Number.isFinite(currentSma[idx]) ? fmtPrice(currentSma[idx]) : (smaPending ? '...' : '-');
1715
- document.getElementById('legend-vwap').textContent = Number.isFinite(currentVwap[idx]) ? fmtPrice(currentVwap[idx]) : '-';
1716
- document.getElementById('legend-sma-init').textContent = Number.isFinite(currentSmaInit[idx]) ? fmtPrice(currentSmaInit[idx]) : '-';
1717
- document.getElementById('legend-ama').textContent = Number.isFinite(currentAma[idx]) ? fmtPrice(currentAma[idx]) : '-';
1718
- }
1719
- function candlePlugin() {
1720
- function drawCandles(u) {
1721
- u.ctx.save();
1722
-
1723
- const offset = 0.5;
1724
- u.ctx.translate(offset, offset);
1725
-
1726
- const [iMin, iMax] = u.series[0].idxs;
1727
-
1728
- for (let i = iMin; i <= iMax; i++) {
1729
- const xVal = u.scales.x.distr == 2 ? i : u.data[0][i];
1730
- const open = u.data[1][i];
1731
- const high = u.data[2][i];
1732
- const low = u.data[3][i];
1733
- const close = u.data[4][i];
1734
-
1735
- const x = u.valToPos(xVal, 'x', true);
1736
- const openY = u.valToPos(open, 'y', true);
1737
- const highY = u.valToPos(high, 'y', true);
1738
- const lowY = u.valToPos(low, 'y', true);
1739
- const closeY = u.valToPos(close, 'y', true);
1740
- if (![x, openY, highY, lowY, closeY].every(Number.isFinite)) continue;
1741
-
1742
- const nextX = i + 1 <= iMax ? u.valToPos(u.scales.x.distr == 2 ? (i + 1) : u.data[0][i + 1], 'x', true) : null;
1743
- const prevX = i - 1 >= iMin ? u.valToPos(u.scales.x.distr == 2 ? (i - 1) : u.data[0][i - 1], 'x', true) : null;
1744
- const spacing = Number.isFinite(nextX) ? (nextX - x) : (Number.isFinite(prevX) ? (x - prevX) : 12);
1745
- // Wider bodies read better when zoomed in and reduce empty space between candles.
1746
- const bodyW = Math.max(
1747
- 4,
1748
- Math.min(
1749
- Math.abs(spacing) * 0.86,
1750
- Math.max(18, Math.abs(spacing) * 0.94),
1751
- ),
1752
- );
1753
- const dir = candleDirection(open, close);
1754
- const bodyColor = dir === 'up' ? '#26a69a' : (dir === 'down' ? '#ef5350' : '#64748b');
1755
- const wickColor = dir === 'up' ? '#b3fff3' : (dir === 'down' ? '#ffb3b3' : '#94a3b8');
1756
- const bodyTop = Math.min(openY, closeY);
1757
- const bodyBottom = Math.max(openY, closeY);
1758
- const bodyH = Math.max(dir === 'flat' ? 2 : 3, Math.round(bodyBottom - bodyTop));
1759
- const bodyX = Math.round(x - bodyW / 2);
1760
- const bodyY = Math.round(bodyTop);
1761
-
1762
- const wickW = Math.max(1, Math.min(5, Math.round(Math.abs(spacing) * 0.14)));
1763
- u.ctx.strokeStyle = wickColor;
1764
- u.ctx.lineWidth = wickW;
1765
- u.ctx.beginPath();
1766
- u.ctx.moveTo(x, highY);
1767
- u.ctx.lineTo(x, lowY);
1768
- u.ctx.stroke();
1769
-
1770
- u.ctx.fillStyle = bodyColor;
1771
- u.ctx.fillRect(bodyX, bodyY, Math.round(bodyW), bodyH);
1772
- if (bodyW > 2 && bodyH > 2) {
1773
- u.ctx.strokeStyle = dir === 'up' ? '#0f7f77' : (dir === 'down' ? '#a92d35' : '#475569');
1774
- u.ctx.lineWidth = 1;
1775
- u.ctx.strokeRect(bodyX + 0.5, bodyY + 0.5, Math.round(bodyW) - 1, bodyH - 1);
1776
- }
1777
- }
1778
-
1779
- u.ctx.translate(-offset, -offset);
1780
- u.ctx.restore();
1781
- }
1782
-
1783
- return {
1784
- opts: (u, opts) => {
1785
- uPlot.assign(opts, {
1786
- cursor: { drag: { x: false, y: false, setScale: false }, focus: { prox: 20 } },
1787
- });
1788
- opts.series.forEach((s, i) => {
1789
- if (i > 0 && i <= 4) {
1790
- s.paths = () => null;
1791
- s.points = { show: false };
1792
- s.stroke = 'transparent';
1793
- }
1794
- });
1795
- },
1796
- hooks: { drawAxes: [drawCandles] },
1797
- };
1798
- }
1799
- function volumePlugin() {
1800
- function drawVolumeBars(u) {
1801
- u.ctx.save();
1802
-
1803
- const offset = 0.5;
1804
- u.ctx.translate(offset, offset);
1805
-
1806
- const [iMin, iMax] = u.series[0].idxs;
1807
- const xVals = u.data[0];
1808
- const volVals = u.data[1];
1809
-
1810
- for (let i = iMin; i <= iMax; i++) {
1811
- const vol = volVals[i];
1812
- if (!Number.isFinite(vol) || vol <= 0) continue;
1813
-
1814
- const xVal = u.scales.x.distr == 2 ? i : xVals[i];
1815
- const x = u.valToPos(xVal, 'x', true);
1816
- const top = u.valToPos(vol, 'y', true);
1817
- const bottom = u.valToPos(0, 'y', true);
1818
- if (![x, top, bottom].every(Number.isFinite)) continue;
1819
-
1820
- const nextX = i + 1 <= iMax ? u.valToPos(u.scales.x.distr == 2 ? (i + 1) : xVals[i + 1], 'x', true) : null;
1821
- const prevX = i - 1 >= iMin ? u.valToPos(u.scales.x.distr == 2 ? (i - 1) : xVals[i - 1], 'x', true) : null;
1822
- const spacing = Number.isFinite(nextX) ? (nextX - x) : (Number.isFinite(prevX) ? (x - prevX) : 12);
1823
- const barW = Math.max(
1824
- 4,
1825
- Math.min(
1826
- Math.abs(spacing) * 0.86,
1827
- Math.max(18, Math.abs(spacing) * 0.94),
1828
- ),
1829
- );
1830
-
1831
- const left = Math.round(x - barW / 2);
1832
- const topY = Math.round(Math.min(top, bottom));
1833
- const h = Math.max(1, Math.round(Math.abs(bottom - top)));
1834
-
1835
- u.ctx.fillStyle = '#ffffff';
1836
- u.ctx.fillRect(left, topY, Math.round(barW), h);
1837
- }
1838
-
1839
- u.ctx.translate(-offset, -offset);
1840
- u.ctx.restore();
1841
- }
1842
-
1843
- return {
1844
- opts: (u, opts) => {
1845
- uPlot.assign(opts, {
1846
- cursor: { drag: { x: false, y: false, setScale: false }, focus: { prox: 20 } },
1847
- });
1848
- opts.series.forEach((s, i) => {
1849
- if (i === 1) {
1850
- s.paths = () => null;
1851
- s.points = { show: false };
1852
- s.stroke = 'transparent';
1853
- s.fill = 'transparent';
1854
- }
1855
- });
1856
- },
1857
- hooks: { drawAxes: [drawVolumeBars] },
1858
- };
1859
- }
1860
- function rangeBandPlugin() {
1861
- function drawRangeBand(u) {
1862
- if (!currentRangeEnabled || !currentAmaEnabled || !currentCandles.length) return;
1863
- const xs = u.data[0];
1864
- if (!Array.isArray(xs) || xs.length === 0) return;
1865
- u.ctx.save();
1866
- u.ctx.beginPath();
1867
- u.ctx.rect(u.bbox.left, u.bbox.top, u.bbox.width, u.bbox.height);
1868
- u.ctx.clip();
1869
- // Behind candles/AMA lines (same trick as the dynamic-weight signal background).
1870
- u.ctx.globalCompositeOperation = 'destination-over';
1871
- const UP_FILL = 'rgba(239,83,80,0.16)';
1872
- const DOWN_FILL = 'rgba(38,166,154,0.16)';
1873
- // Symmetric envelope, always both sides: red [AMA, upper]
1874
- // plus green [lower, AMA] along the whole AMA, tilted by the
1875
- // grid's range scaling. Paint per contiguous valid segment.
1876
- let segTop = [];
1877
- let segBot = [];
1878
- const flush = () => {
1879
- if (segTop.length > 1) {
1880
- u.ctx.fillStyle = UP_FILL;
1881
- u.ctx.beginPath();
1882
- u.ctx.moveTo(segTop[0][0], segTop[0][1]);
1883
- for (let k = 1; k < segTop.length; k++) u.ctx.lineTo(segTop[k][0], segTop[k][1]);
1884
- for (let k = segTop.length - 1; k >= 0; k--) u.ctx.lineTo(segTop[k][0], segTop[k][2]);
1885
- u.ctx.closePath();
1886
- u.ctx.fill();
1887
- }
1888
- if (segBot.length > 1) {
1889
- u.ctx.fillStyle = DOWN_FILL;
1890
- u.ctx.beginPath();
1891
- u.ctx.moveTo(segBot[0][0], segBot[0][1]);
1892
- for (let k = 1; k < segBot.length; k++) u.ctx.lineTo(segBot[k][0], segBot[k][1]);
1893
- for (let k = segBot.length - 1; k >= 0; k--) u.ctx.lineTo(segBot[k][0], segBot[k][2]);
1894
- u.ctx.closePath();
1895
- u.ctx.fill();
1896
- }
1897
- u.ctx.strokeStyle = 'rgba(239,83,80,0.55)';
1898
- u.ctx.lineWidth = 1;
1899
- u.ctx.beginPath();
1900
- segTop.forEach((p, k) => { if (k === 0) u.ctx.moveTo(p[0], p[1]); else u.ctx.lineTo(p[0], p[1]); });
1901
- u.ctx.stroke();
1902
- u.ctx.strokeStyle = 'rgba(38,166,154,0.55)';
1903
- u.ctx.beginPath();
1904
- segBot.forEach((p, k) => { if (k === 0) u.ctx.moveTo(p[0], p[1]); else u.ctx.lineTo(p[0], p[1]); });
1905
- u.ctx.stroke();
1906
- segTop = [];
1907
- segBot = [];
1908
- };
1909
- for (let i = 0; i < xs.length; i++) {
1910
- const a = currentAma[i];
1911
- const up = currentRangeUpper[i];
1912
- const lo = currentRangeLower[i];
1913
- if (!Number.isFinite(a) || a <= 0 || !Number.isFinite(up) || up <= a
1914
- || !Number.isFinite(lo) || lo <= 0 || lo >= a) {
1915
- flush();
1916
- continue;
1917
- }
1918
- const x = u.valToPos(xs[i], 'x', true);
1919
- const yA = u.valToPos(a, 'y', true);
1920
- const yU = u.valToPos(up, 'y', true);
1921
- const yL = u.valToPos(lo, 'y', true);
1922
- if (!Number.isFinite(x) || !Number.isFinite(yA) || !Number.isFinite(yU) || !Number.isFinite(yL)) {
1923
- flush();
1924
- continue;
1925
- }
1926
- segTop.push([x, yU, yA]);
1927
- segBot.push([x, yL, yA]);
1928
- }
1929
- flush();
1930
- u.ctx.restore();
1931
- }
1932
- return { hooks: { draw: [drawRangeBand] } };
1933
- }
1934
- function buildData() {
1935
- const tf = timeframeMap.get(currentTimeframe) || timeframeMap.get(defaultTimeframe.label) || timeframes[0];
1936
- currentSeriesState = getSeriesState(currentPairMode);
1937
- currentSeriesCandles = currentSeriesState.candles;
1938
- currentSeriesCloseValues = currentSeriesState.closeValues;
1939
- const aggregated = aggregateCandles(currentSeriesCandles, tf?.seconds || 3600, tf?.label || currentTimeframe);
1940
- currentCandles = aggregated.candles;
1941
- if (currentCandles.length) {
1942
- xMin = currentCandles[0].time;
1943
- xMax = currentCandles[currentCandles.length - 1].time;
1944
- }
1945
- currentDisplayCandles = deriveDisplayCandles(currentCandles);
1946
- currentOpen = currentDisplayCandles.map((c) => c.open);
1947
- currentHigh = currentCandles.map((c) => c.high);
1948
- currentLow = currentCandles.map((c) => c.low);
1949
- currentClose = currentDisplayCandles.map((c) => c.close);
1950
- const baseAma = currentAmaEnabled ? computeAMA(currentSeriesCandles, currentAmaConfig()) : [];
1951
- const baseAmaOff = currentAmaEnabled && currentAmaInitOffset !== 0
1952
- ? computeAMA(currentSeriesCandles, currentAmaConfig(), currentAmaInitOffset)
1953
- : [];
1954
- const baseVwap = currentVwapEnabled ? computeVWMA(currentSeriesCandles, currentVwapBars) : [];
1955
- if (currentSmaEnabled) {
1956
- const smaKey = getSmaCacheKey(currentSmaPeriod);
1957
- const baseSma = smaCache.get(smaKey);
1958
- if (baseSma) {
1959
- currentSma = sampleSeriesByIndex(baseSma, aggregated.idxs);
1960
- } else {
1961
- currentSma = new Array(currentCandles.length).fill(null);
1962
- requestSMA(currentSmaPeriod);
1963
- }
1964
- } else {
1965
- currentSma = new Array(currentCandles.length).fill(null);
1966
- }
1967
- currentAma = currentAmaEnabled ? sampleSeriesByIndex(baseAma, aggregated.idxs) : new Array(currentCandles.length).fill(null);
1968
- const baseRange = computeRangeBand(baseAma);
1969
- currentRangeUpper = sampleSeriesByIndex(baseRange.upper, aggregated.idxs);
1970
- currentRangeLower = sampleSeriesByIndex(baseRange.lower, aggregated.idxs);
1971
- currentAmaOff = currentAmaEnabled && currentAmaInitOffset !== 0 ? sampleSeriesByIndex(baseAmaOff, aggregated.idxs) : new Array(currentCandles.length).fill(null);
1972
- currentVwap = currentVwapEnabled ? sampleSeriesByIndex(baseVwap, aggregated.idxs) : new Array(currentCandles.length).fill(null);
1973
- const amaCfg = currentAmaConfig();
1974
- const warmupInit = currentAmaEnabled && baseAma.length > amaCfg.erPeriod ? baseAma[amaCfg.erPeriod] : null;
1975
- // Build the init segment in the selected timeframe. Sampling the
1976
- // 1h init series by each bucket's final 1h index can make it end
1977
- // inside a week/month bucket, leaving a gap before the first
1978
- // sampled AMA value appears.
1979
- const firstAmaIndex = currentAma.findIndex((value) => Number.isFinite(value));
1980
- // The first visible higher-timeframe AMA sample can already be
1981
- // several 1h updates past the true warmup point. Anchor that
1982
- // sample to the warmup average so the AMA starts where the init
1983
- // line ends instead of appearing detached at a different value.
1984
- if (warmupInit !== null && firstAmaIndex >= 0) currentAma[firstAmaIndex] = warmupInit;
1985
- currentSmaInit = warmupInit !== null
1986
- ? currentAma.map((value, i) => i <= firstAmaIndex || (firstAmaIndex < 0 && i === currentAma.length - 1) ? warmupInit : null)
1987
- : new Array(currentCandles.length).fill(null);
1988
- const offsetInit = currentAmaEnabled && currentAmaInitOffset !== 0 && baseAmaOff.length > amaCfg.erPeriod
1989
- ? baseAmaOff[amaCfg.erPeriod]
1990
- : null;
1991
- const firstAmaOffIndex = currentAmaOff.findIndex((value) => Number.isFinite(value));
1992
- currentSmaInitOff = offsetInit !== null
1993
- ? currentAmaOff.map((value, i) => i < firstAmaOffIndex || (firstAmaOffIndex < 0 && i === currentAmaOff.length - 1) ? offsetInit : null)
1994
- : new Array(currentCandles.length).fill(null);
1995
- currentPriceData = [
1996
- currentCandles.map((c) => c.time),
1997
- currentOpen,
1998
- currentHigh,
1999
- currentLow,
2000
- currentClose,
2001
- currentSma,
2002
- currentAma,
2003
- currentVwap,
2004
- currentSmaInit,
2005
- currentSmaInitOff,
2006
- currentAmaOff,
2007
- ];
2008
- currentVolumeData = [
2009
- currentCandles.map((c) => c.time),
2010
- currentCandles.map((c) => getDisplayVolume(c)),
2011
- ];
2012
- return {
2013
- priceData: currentPriceData,
2014
- volumeData: currentVolumeData,
2015
- };
2016
- }
2017
- function makeChart() {
2018
- const data = buildData();
2019
- const isLogScale = currentPriceScale !== 'linear';
2020
-
2021
- const priceOpts = {
2022
- width: priceEl.clientWidth,
2023
- height: priceEl.clientHeight,
2024
- padding: [14, 8, 8, 8],
2025
- legend: { show: false },
2026
- select: { show: false },
2027
- cursor: { sync: { key: SYNC_KEY, setSeries: false, scales: ['x', null] }, drag: { x: false, y: false, setScale: false }, focus: { prox: 20 } },
2028
- scales: {
2029
- x: { time: true },
2030
- y: {
2031
- auto: true,
2032
- distr: isLogScale ? 3 : 1,
2033
- log: isLogScale ? 10 : undefined,
2034
- range: (u, min, max) => {
2035
- if (manualYRange) return [manualYRange.min, manualYRange.max];
2036
- const vis = visiblePriceRange(u);
2037
- if (vis) return vis;
2038
- if (isLogScale) {
2039
- if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || max <= 0) return [1, 10];
2040
- } else if (!Number.isFinite(min) || !Number.isFinite(max)) {
2041
- return [0, 1];
2042
- }
2043
- return [min * 0.97, max * 1.03];
2044
- },
2045
- },
2046
- },
2047
- series: [
2048
- { label: 'Time' },
2049
- { label: 'Open' },
2050
- { label: 'High' },
2051
- { label: 'Low' },
2052
- { label: 'Close' },
2053
- { label: 'SMA', stroke: '#ffffff', width: 2, points: { show: false }, spanGaps: true },
2054
- { label: 'AMA', stroke: '#facc15', width: 2, points: { show: false }, spanGaps: true },
2055
- { label: 'VWMA', stroke: '#93c5fd', width: 2, points: { show: false }, spanGaps: true },
2056
- { label: 'AMA Init', stroke: '#22c55e', width: 1.5, dash: [6, 4], points: { show: false }, spanGaps: false },
2057
- { label: 'Off Init', stroke: '#a855f7', width: 1.5, dash: [6, 4], points: { show: false }, spanGaps: false },
2058
- { label: 'AMA Off', stroke: '#a855f7', width: 1.5, dash: [4, 4], points: { show: false }, spanGaps: false },
2059
- ],
2060
- axes: [
2061
- makeTimeAxis(false),
2062
- {
2063
- scale: 'y',
2064
- side: 1,
2065
- size: 84,
2066
- space: isLogScale ? 1 : 45,
2067
- stroke: '#ffffff',
2068
- grid: { stroke: '#272f3a' },
2069
- ticks: { stroke: '#414b57', width: 1 },
2070
- font: '600 13px Segoe UI, sans-serif',
2071
- splits: isLogScale ? logAxisSplits : undefined,
2072
- values: (u, vals) => isLogScale
2073
- ? vals.map((v) => (Number.isFinite(v) ? fmtPrice(v) : ''))
2074
- : fmtPriceAxis(vals),
2075
- },
2076
- ],
2077
- hooks: {
2078
- draw: [(u) => { positionPriceMarker(u); positionReserveLine(u); positionOrderLines(u); positionUpdateMarker(u, true); }],
2079
- // Keep the bottom-right stat badges glued to the visible
2080
- // window while zooming/panning (rAF-throttled text swap).
2081
- // Refit Y to the visible window on timeframe (x) moves —
2082
- // uPlot does not recompute Y on setScale('x') by itself.
2083
- setScale: [(u, key) => { if (key === 'x') scheduleYRefit(); scheduleStatPanels(); }],
2084
- },
2085
- };
2086
-
2087
- const plugin = candlePlugin();
2088
- plugin.opts(null, priceOpts);
2089
- priceOpts.plugins = [rangeBandPlugin(), plugin];
2090
- if (!priceChart) priceChart = new uPlot(priceOpts, data.priceData, priceEl);
2091
- else priceChart.setData(data.priceData, false);
2092
-
2093
- const volumeOpts = {
2094
- width: volumeEl.clientWidth,
2095
- height: volumeEl.clientHeight,
2096
- padding: [6, 8, 8, 8],
2097
- legend: { show: false },
2098
- select: { show: false },
2099
- cursor: { sync: { key: SYNC_KEY, setSeries: false, scales: ['x', null] }, drag: { x: false, y: false, setScale: false }, focus: { prox: 20 } },
2100
- scales: {
2101
- x: { time: true },
2102
- y: {
2103
- auto: true,
2104
- range: (u, min, max) => {
2105
- const vis = visibleVolumeRange(u);
2106
- if (vis) return vis;
2107
- if (!Number.isFinite(min) || !Number.isFinite(max) || max <= 0) return [0, 1];
2108
- return [0, max * 1.15];
2109
- },
2110
- },
2111
- },
2112
- series: [
2113
- { label: 'Time' },
2114
- { label: 'Volume', stroke: '#ffffff', fill: '#ffffff', width: 1, points: { show: false } },
2115
- ],
2116
- axes: [
2117
- makeTimeAxis(true),
2118
- { scale: 'y', side: 1, size: 84, space: 22, stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, font: '600 12px Segoe UI, sans-serif', values: (u, vals) => vals.map((v) => (v == null ? '' : fmtVolume(v))) },
2119
- ],
2120
- hooks: {
2121
- // x is synced from the price chart; refit volume Y to the
2122
- // visible window and refresh the max badge.
2123
- setScale: [(u, key) => { if (key === 'x') scheduleYRefit(); scheduleStatPanels(); }],
2124
- },
2125
- };
2126
-
2127
- const volumePluginInst = volumePlugin();
2128
- volumePluginInst.opts(null, volumeOpts);
2129
- volumeOpts.plugins = [volumePluginInst];
2130
- if (!volumeChart) volumeChart = new uPlot(volumeOpts, data.volumeData, volumeEl);
2131
- else volumeChart.setData(data.volumeData, false);
2132
-
2133
- charts = [priceChart, volumeChart];
2134
- lastRenderedPriceScale = currentPriceScale;
2135
- return priceChart;
2136
- }
2137
- // True when clientX sits over the true price-axis gutter (right of
2138
- // the plot area). Keyed off uPlot's plot rect, not the container
2139
- // width, so grabs on candles — even the newest ones at the plot's
2140
- // right edge — always pan instead of scaling. Only the axis itself
2141
- // zooms price; the rest pans time.
2142
- function inYAxisZone(chart, clientX) {
2143
- if (chart !== priceChart || !chart.over) return false;
2144
- const overRect = chart.over.getBoundingClientRect();
2145
- if (!overRect || overRect.width <= 0) return false;
2146
- return clientX >= overRect.right - 2;
2147
- }
2148
- // True when the pointer sits over the time-axis gutter (below the
2149
- // plot area) of either chart. Dragging there scales the timeframe;
2150
- // drags on candles always pan instead.
2151
- function inXAxisZone(chart, clientY) {
2152
- if (!chart || !chart.over) return false;
2153
- const overRect = chart.over.getBoundingClientRect();
2154
- if (!overRect || overRect.height <= 0) return false;
2155
- return clientY >= overRect.bottom - 2;
2156
- }
2157
- let priceMarkerLabel = null;
2158
- function ensurePriceMarker(u) {
2159
- if (priceMarkerLabel && priceMarkerLabel.parentNode === u.root) return;
2160
- if (priceMarkerLabel && priceMarkerLabel.parentNode) priceMarkerLabel.parentNode.removeChild(priceMarkerLabel);
2161
- try { if (getComputedStyle(u.root).position === 'static') u.root.style.position = 'relative'; } catch (e) {}
2162
- priceMarkerLabel = document.createElement('div');
2163
- priceMarkerLabel.style.cssText = 'position:absolute;z-index:30;pointer-events:none;font:600 12px Segoe UI, sans-serif;line-height:19px;height:19px;padding:0 7px;border-radius:3px;color:#ffffff;white-space:nowrap;box-sizing:border-box;text-align:center;overflow:hidden;';
2164
- u.root.appendChild(priceMarkerLabel);
2165
- }
2166
- function positionPriceMarker(u) {
2167
- if (!u || !u.over || !currentCandles.length) return;
2168
- ensurePriceMarker(u);
2169
- const last = currentCandles[currentCandles.length - 1];
2170
- const prev = currentCandles.length > 1 ? currentCandles[currentCandles.length - 2] : last;
2171
- const price = last.close;
2172
- if (!Number.isFinite(price)) {
2173
- priceMarkerLabel.style.display = 'none';
2174
- return;
2175
- }
2176
- const up = price >= (Number.isFinite(prev.close) ? prev.close : price);
2177
- const color = up ? '#26a69a' : '#ef5350';
2178
- const s = u.scales.y || {};
2179
- const sMin = Number.isFinite(s.min) ? s.min : null;
2180
- const sMax = Number.isFinite(s.max) ? s.max : null;
2181
- if (sMin == null || sMax == null || sMax <= sMin) {
2182
- priceMarkerLabel.style.display = 'none';
2183
- return;
2184
- }
2185
- let frac;
2186
- if (currentPriceScale === 'log') {
2187
- const lmin = Math.log10(sMin);
2188
- const lmax = Math.log10(sMax);
2189
- const lp = Math.log10(Math.max(price, 1e-12));
2190
- frac = (lp - lmin) / (lmax - lmin);
2191
- } else {
2192
- frac = (price - sMin) / (sMax - sMin);
2193
- }
2194
- const rootRect = u.root.getBoundingClientRect();
2195
- const overRect = u.over.getBoundingClientRect();
2196
- if (!overRect || overRect.height <= 0) return;
2197
- const plotTop = overRect.top - rootRect.top;
2198
- const yRel = (1 - frac) * overRect.height;
2199
- // No full-width dashed line by design (disturbs reading) — the
2200
- // axis label above carries the last price on its own.
2201
- priceMarkerLabel.style.display = 'block';
2202
- priceMarkerLabel.textContent = fmtPriceLabel(price);
2203
- priceMarkerLabel.style.background = color;
2204
- priceMarkerLabel.style.top = (plotTop + Math.max(0, Math.min(overRect.height, yRel)) - 10) + 'px';
2205
- const leftAxisW = overRect.left - rootRect.left;
2206
- const rightAxisW = rootRect.right - overRect.right;
2207
- if (leftAxisW >= rightAxisW) {
2208
- priceMarkerLabel.style.left = '0px';
2209
- priceMarkerLabel.style.right = '';
2210
- priceMarkerLabel.style.width = Math.max(40, leftAxisW - 4) + 'px';
2211
- } else {
2212
- priceMarkerLabel.style.left = '';
2213
- priceMarkerLabel.style.right = '0px';
2214
- priceMarkerLabel.style.width = Math.max(40, rightAxisW - 4) + 'px';
2215
- }
2216
- }
2217
- // ── Order overlay ──
2218
- // Active grid orders as dashed levels: green = buys, red = sells.
2219
- // Grid bounds span the full grid (live + virtual slots), never
2220
- // calculated: reserve = lowest grid buy, ceiling = highest grid sell.
2221
- // Spread = best buy/best sell gap.
2222
- // Pair-aware: order prices invert (1/p) with the candles so B/A shows
2223
- // the same levels in display units (side colors preserved).
2224
- let reserveLine = null;
2225
- let reserveLabel = null;
2226
- let ceilingLine = null;
2227
- let ceilingLabel = null;
2228
- let spreadMidLabel = null;
2229
- let orderLineDivs = [];
2230
- let orderBuyLabel = null;
2231
- let orderSellLabel = null;
2232
- let orderPriceTags = [];
2233
- let lastOverlayKey = '';
2234
- function getDisplayOrders() {
2235
- const rawBuys = Array.isArray(payload.orderBuys) ? payload.orderBuys.filter(Number.isFinite).filter((p) => p > 0) : [];
2236
- const rawSells = Array.isArray(payload.orderSells) ? payload.orderSells.filter(Number.isFinite).filter((p) => p > 0) : [];
2237
- if (normalizePairMode(currentPairMode) !== 'inverse') return { buys: rawBuys, sells: rawSells };
2238
- const inv = (arr) => arr.map((p) => 1 / p).filter(Number.isFinite).filter((p) => p > 0);
2239
- return { buys: inv(rawBuys), sells: inv(rawSells) };
2240
- }
2241
- function yForPriceCached(ys, overRect, rootRect, price) {
2242
- const sMin = Number.isFinite(ys.min) ? ys.min : null;
2243
- const sMax = Number.isFinite(ys.max) ? ys.max : null;
2244
- if (sMin == null || sMax == null || sMax <= sMin) return null;
2245
- let frac;
2246
- if (currentPriceScale === 'log') {
2247
- if (!(sMin > 0) || !(price > 0)) return null;
2248
- const lmin = Math.log10(sMin), lmax = Math.log10(sMax);
2249
- frac = (Math.log10(price) - lmin) / (lmax - lmin);
2250
- } else {
2251
- frac = (price - sMin) / (sMax - sMin);
2252
- }
2253
- if (frac < 0 || frac > 1) return null;
2254
- return (overRect.top - rootRect.top) + (1 - frac) * overRect.height;
2255
- }
2256
- function hideOverlayNodes() {
2257
- [reserveLine, reserveLabel, ceilingLine, ceilingLabel, spreadMidLabel, orderBuyLabel, orderSellLabel].forEach((n) => { if (n) n.style.display = 'none'; });
2258
- orderLineDivs.forEach((d) => { d.style.display = 'none'; });
2259
- orderPriceTags.forEach((t) => { t.style.display = 'none'; });
2260
- }
2261
- function positionReserveLine(u) {
2262
- if (!u || !u.over || !currentCandles.length) return;
2263
- if (!currentOrdersVisible || (!hasOrders && !hasBounds)) { hideOverlayNodes(); return; }
2264
- try { if (getComputedStyle(u.root).position === 'static') u.root.style.position = 'relative'; } catch (e) {}
2265
- if (!reserveLine || reserveLine.parentNode !== u.root) {
2266
- if (reserveLine && reserveLine.parentNode) reserveLine.parentNode.removeChild(reserveLine);
2267
- if (reserveLabel && reserveLabel.parentNode) reserveLabel.parentNode.removeChild(reserveLabel);
2268
- reserveLine = document.createElement('div');
2269
- reserveLine.style.cssText = 'position:absolute;z-index:1;pointer-events:none;height:0;border-top:2px dashed #f97316;opacity:0.7;left:0;right:0;display:none;';
2270
- reserveLabel = document.createElement('div');
2271
- reserveLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 10px Segoe UI, sans-serif;line-height:15px;height:15px;padding:0 5px;border-radius:3px;color:#f97316;background:rgba(30,41,59,0.9);white-space:nowrap;display:none;';
2272
- u.root.appendChild(reserveLine);
2273
- u.root.appendChild(reserveLabel);
2274
- }
2275
- // Grid bounds span the full DEXBot grid (live + virtual slots
2276
- // in base units), never calculated: bottom = lowest grid buy,
2277
- // top = highest grid sell. Reciprocals flip the ordering, so
2278
- // the sides swap in B/A view. A missing side hides its line
2279
- // instead of drawing an invented level.
2280
- const { buys: boundBuys, sells: boundSells } = getDisplayOrders();
2281
- const rawLow = Number(payload.gridBounds?.low);
2282
- const rawHigh = Number(payload.gridBounds?.high);
2283
- const gridLow = Number.isFinite(rawLow) && rawLow > 0 ? rawLow : null;
2284
- const gridHigh = Number.isFinite(rawHigh) && rawHigh > 0 ? rawHigh : null;
2285
- const inversePairs = normalizePairMode(currentPairMode) === 'inverse';
2286
- const reservePrice = inversePairs
2287
- ? (gridHigh != null ? 1 / gridHigh : null)
2288
- : gridLow;
2289
- const ceilingPrice = inversePairs
2290
- ? (gridLow != null ? 1 / gridLow : null)
2291
- : gridHigh;
2292
- const ys = u.scales.y || {};
2293
- const rootRect = u.root.getBoundingClientRect();
2294
- const overRect = u.over.getBoundingClientRect();
2295
- const y = reservePrice != null ? yForPriceCached(ys, overRect, rootRect, reservePrice) : null;
2296
- if (y == null) {
2297
- reserveLine.style.display = 'none';
2298
- reserveLabel.style.display = 'none';
2299
- } else {
2300
- reserveLine.style.display = 'block';
2301
- reserveLine.style.top = y + 'px';
2302
- const lastClose = currentCandles[currentCandles.length - 1].close;
2303
- const dipRaw = Number.isFinite(lastClose) && lastClose > 0 ? (lastClose - reservePrice) / lastClose * 100 : NaN;
2304
- const dipTxt = Number.isFinite(dipRaw) ? (dipRaw >= 0 ? '-' : '+') + Math.abs(Math.round(dipRaw)) + '%' : '-';
2305
- reserveLabel.style.display = 'block';
2306
- reserveLabel.textContent = 'reserve ' + fmtPriceLabel(reservePrice) + ' (' + dipTxt + ')';
2307
- reserveLabel.style.left = '8px';
2308
- reserveLabel.style.top = (y - 16) + 'px';
2309
- }
2310
- if (!ceilingLine || ceilingLine.parentNode !== u.root) {
2311
- if (ceilingLine && ceilingLine.parentNode) ceilingLine.parentNode.removeChild(ceilingLine);
2312
- if (ceilingLabel && ceilingLabel.parentNode) ceilingLabel.parentNode.removeChild(ceilingLabel);
2313
- ceilingLine = document.createElement('div');
2314
- ceilingLine.style.cssText = 'position:absolute;z-index:1;pointer-events:none;height:0;border-top:2px dashed #f97316;opacity:0.7;left:0;right:0;display:none;';
2315
- ceilingLabel = document.createElement('div');
2316
- ceilingLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 10px Segoe UI, sans-serif;line-height:15px;height:15px;padding:0 5px;border-radius:3px;color:#f97316;background:rgba(30,41,59,0.9);white-space:nowrap;display:none;';
2317
- u.root.appendChild(ceilingLine);
2318
- u.root.appendChild(ceilingLabel);
2319
- }
2320
- const cY = ceilingPrice != null ? yForPriceCached(ys, overRect, rootRect, ceilingPrice) : null;
2321
- if (cY == null) {
2322
- ceilingLine.style.display = 'none';
2323
- ceilingLabel.style.display = 'none';
2324
- } else {
2325
- ceilingLine.style.display = 'block';
2326
- ceilingLine.style.top = cY + 'px';
2327
- const lastCloseTop = currentCandles[currentCandles.length - 1].close;
2328
- const upRaw = Number.isFinite(lastCloseTop) && lastCloseTop > 0 ? (ceilingPrice - lastCloseTop) / lastCloseTop * 100 : NaN;
2329
- const upTxt = Number.isFinite(upRaw) ? (upRaw >= 0 ? '+' : '-') + Math.abs(Math.round(upRaw)) + '%' : '-';
2330
- ceilingLabel.style.display = 'block';
2331
- ceilingLabel.textContent = 'top ' + fmtPriceLabel(ceilingPrice) + ' (' + upTxt + ')';
2332
- ceilingLabel.style.left = '8px';
2333
- ceilingLabel.style.top = (cY + 4) + 'px';
2334
- }
2335
- if (!spreadMidLabel || spreadMidLabel.parentNode !== u.root) {
2336
- if (spreadMidLabel && spreadMidLabel.parentNode) spreadMidLabel.parentNode.removeChild(spreadMidLabel);
2337
- spreadMidLabel = document.createElement('div');
2338
- spreadMidLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:700 11px Segoe UI, sans-serif;line-height:16px;height:16px;padding:0 6px;border-radius:3px;color:#0b0f14;background:#facc15;white-space:nowrap;display:none;';
2339
- u.root.appendChild(spreadMidLabel);
2340
- }
2341
- if (boundBuys.length && boundSells.length) {
2342
- const bestBuy = Math.max(...boundBuys);
2343
- const bestSell = Math.min(...boundSells);
2344
- const yB = yForPriceCached(ys, overRect, rootRect, bestBuy);
2345
- const yS = yForPriceCached(ys, overRect, rootRect, bestSell);
2346
- if (yB != null && yS != null && bestBuy > 0) {
2347
- const spr = (bestSell - bestBuy) / bestBuy * 100;
2348
- spreadMidLabel.style.display = 'block';
2349
- spreadMidLabel.textContent = 'spread ' + spr.toFixed(2) + '%';
2350
- spreadMidLabel.style.left = '8px';
2351
- spreadMidLabel.style.top = ((yB + yS) / 2 - 8) + 'px';
2352
- } else {
2353
- spreadMidLabel.style.display = 'none';
2354
- }
2355
- } else if (spreadMidLabel) {
2356
- spreadMidLabel.style.display = 'none';
2357
- }
2358
- }
2359
- function positionOrderLines(u) {
2360
- if (!u || !u.over) return;
2361
- if (!currentOrdersVisible) {
2362
- orderLineDivs.forEach((d) => { d.style.display = 'none'; });
2363
- orderPriceTags.forEach((t) => { t.style.display = 'none'; });
2364
- if (orderBuyLabel) orderBuyLabel.style.display = 'none';
2365
- if (orderSellLabel) orderSellLabel.style.display = 'none';
2366
- return;
2367
- }
2368
- try { if (getComputedStyle(u.root).position === 'static') u.root.style.position = 'relative'; } catch (e) {}
2369
- const { buys, sells } = getDisplayOrders();
2370
- const total = buys.length + sells.length;
2371
- if (orderLineDivs.length && orderLineDivs[0].parentNode !== u.root) {
2372
- orderLineDivs.forEach((d) => u.root.appendChild(d));
2373
- orderPriceTags.forEach((t) => u.root.appendChild(t));
2374
- lastOverlayKey = '';
2375
- }
2376
- while (orderLineDivs.length < total) {
2377
- const d = document.createElement('div');
2378
- d.style.cssText = 'position:absolute;z-index:1;pointer-events:none;height:0;left:0;right:0;display:none;';
2379
- u.root.appendChild(d);
2380
- orderLineDivs.push(d);
2381
- }
2382
- const ys = u.scales.y || {};
2383
- const overlayKey = (ys.min || 0) + '|' + (ys.max || 0) + '|' + (u.root.clientWidth || 0) + '|' + (u.root.clientHeight || 0) + '|' + currentPriceScale + '|' + currentPairMode;
2384
- if (overlayKey === lastOverlayKey) return;
2385
- lastOverlayKey = overlayKey;
2386
- const rootRect = u.root.getBoundingClientRect();
2387
- const overRect = u.over.getBoundingClientRect();
2388
- if (!orderBuyLabel || orderBuyLabel.parentNode !== u.root) {
2389
- if (orderBuyLabel && orderBuyLabel.parentNode) orderBuyLabel.parentNode.removeChild(orderBuyLabel);
2390
- orderBuyLabel = document.createElement('div');
2391
- orderBuyLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 10px Segoe UI, sans-serif;line-height:15px;height:15px;padding:0 5px;border-radius:3px;color:#26a69a;background:rgba(30,41,59,0.9);white-space:nowrap;display:none;';
2392
- u.root.appendChild(orderBuyLabel);
2393
- }
2394
- if (!orderSellLabel || orderSellLabel.parentNode !== u.root) {
2395
- if (orderSellLabel && orderSellLabel.parentNode) orderSellLabel.parentNode.removeChild(orderSellLabel);
2396
- orderSellLabel = document.createElement('div');
2397
- orderSellLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 10px Segoe UI, sans-serif;line-height:15px;height:15px;padding:0 5px;border-radius:3px;color:#ef5350;background:rgba(30,41,59,0.9);white-space:nowrap;display:none;';
2398
- u.root.appendChild(orderSellLabel);
2399
- }
2400
- let idx = 0;
2401
- const place = (price, color) => {
2402
- const d = orderLineDivs[idx++];
2403
- const y = yForPriceCached(ys, overRect, rootRect, price);
2404
- if (y == null) { d.style.display = 'none'; return null; }
2405
- d.style.display = 'block';
2406
- d.style.top = y + 'px';
2407
- d.style.borderTop = '1.5px dashed ' + color;
2408
- d.style.opacity = '0.55';
2409
- return y;
2410
- };
2411
- let botBuyY = null;
2412
- buys.forEach((p) => { const y = place(p, '#26a69a'); if (y != null && (botBuyY == null || y > botBuyY)) botBuyY = y; });
2413
- let topSellY = null;
2414
- sells.forEach((p) => { const y = place(p, '#ef5350'); if (y != null && (topSellY == null || y < topSellY)) topSellY = y; });
2415
- for (; idx < orderLineDivs.length; idx++) orderLineDivs[idx].style.display = 'none';
2416
- if (orderPriceTags.length && orderPriceTags[0].parentNode !== u.root) {
2417
- orderPriceTags.forEach((t) => u.root.appendChild(t));
2418
- }
2419
- const levels = [
2420
- ...buys.map((p) => ({ p, c: '#26a69a', bg: 'rgba(20,30,28,0.92)' })),
2421
- ...sells.map((p) => ({ p, c: '#ef5350', bg: 'rgba(30,20,22,0.92)' })),
2422
- ].sort((a, b) => a.p - b.p);
2423
- let ti = 0, lastTagY = -Infinity;
2424
- const ensureTag = () => {
2425
- if (ti >= orderPriceTags.length) {
2426
- const t = document.createElement('div');
2427
- t.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 9px Segoe UI, sans-serif;line-height:14px;height:14px;padding:0 4px;border-radius:3px;white-space:nowrap;display:none;';
2428
- u.root.appendChild(t);
2429
- orderPriceTags.push(t);
2430
- }
2431
- return orderPriceTags[ti++];
2432
- };
2433
- for (const lv of levels) {
2434
- const tag = ensureTag();
2435
- const y = yForPriceCached(ys, overRect, rootRect, lv.p);
2436
- if (y == null || Math.abs(y - lastTagY) < 13) { tag.style.display = 'none'; continue; }
2437
- tag.style.display = 'block';
2438
- tag.style.top = (y - 7) + 'px';
2439
- tag.style.right = '4px';
2440
- tag.style.color = lv.c;
2441
- tag.style.background = lv.bg;
2442
- tag.style.border = '1px solid ' + lv.c;
2443
- tag.textContent = fmtPriceLabel(lv.p);
2444
- lastTagY = y;
2445
- }
2446
- for (; ti < orderPriceTags.length; ti++) orderPriceTags[ti].style.display = 'none';
2447
- if (buys.length && botBuyY != null) {
2448
- orderBuyLabel.style.display = 'block';
2449
- orderBuyLabel.textContent = 'BUYS (' + buys.length + ') ' + fmtPriceLabel(Math.min(...buys));
2450
- orderBuyLabel.style.left = '8px';
2451
- orderBuyLabel.style.top = (botBuyY + 4) + 'px';
2452
- } else {
2453
- orderBuyLabel.style.display = 'none';
2454
- }
2455
- if (sells.length && topSellY != null) {
2456
- orderSellLabel.style.display = 'block';
2457
- orderSellLabel.textContent = 'SELLS (' + sells.length + ') ' + fmtPriceLabel(Math.max(...sells));
2458
- orderSellLabel.style.left = '8px';
2459
- orderSellLabel.style.top = (topSellY - 16) + 'px';
2460
- } else {
2461
- orderSellLabel.style.display = 'none';
2462
- }
2463
- }
2464
- function resetOverlayNodes() {
2465
- reserveLine = null;
2466
- reserveLabel = null;
2467
- ceilingLine = null;
2468
- ceilingLabel = null;
2469
- spreadMidLabel = null;
2470
- orderLineDivs = [];
2471
- orderBuyLabel = null;
2472
- orderSellLabel = null;
2473
- orderPriceTags = [];
2474
- lastOverlayKey = '';
2475
- }
2476
- // ── Volume hover tooltip ──
2477
- let volumeHoverTip = null;
2478
- // ── Update marker ("updated from here"): vertical line where the
2479
- // latest incremental fetch started, with a date label. Shown only
2480
- // when the generator was given a marker timestamp.
2481
- const UPDATE_MARKER_SEC = Number(payload.updateMarkerTsSec) > 0 ? Number(payload.updateMarkerTsSec) : null;
2482
- function positionUpdateMarker(u, withLabel) {
2483
- if (!UPDATE_MARKER_SEC || !u || !u.over || !currentCandles.length) return;
2484
- let wrap = u.root.querySelector(':scope > .um-wrap');
2485
- if (!wrap) {
2486
- try { if (getComputedStyle(u.root).position === 'static') u.root.style.position = 'relative'; } catch (e) {}
2487
- wrap = document.createElement('div');
2488
- wrap.className = 'um-wrap';
2489
- wrap.style.cssText = 'position:absolute;z-index:24;pointer-events:none;';
2490
- wrap.innerHTML =
2491
- '<div class="um-line" style="position:absolute;top:0;height:100%;width:0;border-left:2px dashed #22d3ee;opacity:0.75;"></div>' +
2492
- '<div class="um-tag" style="position:absolute;top:2px;left:6px;font:600 10px Segoe UI, sans-serif;line-height:15px;color:#22d3ee;white-space:nowrap;"></div>';
2493
- u.root.appendChild(wrap);
2494
- }
2495
- const s = u.scales.x || {};
2496
- const sMin = Number.isFinite(s.min) ? s.min : null;
2497
- const sMax = Number.isFinite(s.max) ? s.max : null;
2498
- if (sMin == null || sMax == null || sMax <= sMin) { wrap.style.display = 'none'; return; }
2499
- const frac = (UPDATE_MARKER_SEC - sMin) / (sMax - sMin);
2500
- const inView = frac >= 0 && frac <= 1;
2501
- if (!inView) { wrap.style.display = 'none'; return; }
2502
- const rootRect = u.root.getBoundingClientRect();
2503
- const overRect = u.over.getBoundingClientRect();
2504
- const xRoot = (overRect.left - rootRect.left) + frac * overRect.width;
2505
- wrap.style.display = 'block';
2506
- wrap.style.left = xRoot + 'px';
2507
- wrap.style.top = (overRect.top - rootRect.top) + 'px';
2508
- wrap.style.height = overRect.height + 'px';
2509
- if (withLabel) {
2510
- const tag = wrap.querySelector('.um-tag');
2511
- const d = new Date(UPDATE_MARKER_SEC * 1000);
2512
- const hh = String(d.getUTCHours()).padStart(2, '0');
2513
- const mm = String(d.getUTCMinutes()).padStart(2, '0');
2514
- const bars = Number(payload.updateMarkerNewBars) > 0 ? ' (+' + Math.round(Number(payload.updateMarkerNewBars)) + ')' : '';
2515
- tag.textContent = 'update ' + d.toLocaleDateString(undefined) + ' ' + hh + ':' + mm + bars + ' →';
2516
- tag.style.left = (frac > 0.8 ? -(tag.offsetWidth + 8) : 6) + 'px';
2517
- }
2518
- }
2519
- function ensureVolumeHoverTip(u) {
2520
- if (volumeHoverTip && volumeHoverTip.parentNode === u.root) return;
2521
- if (volumeHoverTip && volumeHoverTip.parentNode) volumeHoverTip.parentNode.removeChild(volumeHoverTip);
2522
- volumeHoverTip = document.createElement('div');
2523
- volumeHoverTip.style.cssText = 'position:absolute;z-index:31;pointer-events:none;display:none;font:600 11px Segoe UI, sans-serif;line-height:18px;height:18px;padding:0 8px;border-radius:4px;color:#ffffff;background:rgba(48,54,61,0.95);border:1px solid #6e7681;white-space:nowrap;box-sizing:border-box;';
2524
- u.root.appendChild(volumeHoverTip);
2525
- }
2526
- function showVolumeHover(u) {
2527
- if (!u || !u.over || !currentCandles.length) return;
2528
- ensureVolumeHoverTip(u);
2529
- const idx = u.cursor.idx;
2530
- if (idx == null || idx < 0 || idx >= currentCandles.length) {
2531
- volumeHoverTip.style.display = 'none';
2532
- return;
2533
- }
2534
- const c = currentCandles[idx];
2535
- const dv = getDisplayVolume(c);
2536
- if (!Number.isFinite(dv)) {
2537
- volumeHoverTip.style.display = 'none';
2538
- return;
2539
- }
2540
- const barX = u.valToPos(u.data[0][idx], 'x', true);
2541
- volumeHoverTip.style.display = 'block';
2542
- volumeHoverTip.textContent = 'Vol ' + fmtVolumeWithSym(dv);
2543
- volumeHoverTip.style.left = Math.max(2, barX - volumeHoverTip.offsetWidth / 2) + 'px';
2544
- // Pinned to the panel top — never covers the bars
2545
- volumeHoverTip.style.top = '2px';
2546
- }
2547
- function currentYRange(chart) {
2548
- const s = chart.scales.y || {};
2549
- let min = Number.isFinite(s.min) ? s.min : null;
2550
- let max = Number.isFinite(s.max) ? s.max : null;
2551
- if (min == null || max == null) {
2552
- const vis = visiblePriceRange(chart);
2553
- if (vis) { min = vis[0]; max = vis[1]; }
2554
- }
2555
- if (min == null || max == null || !Number.isFinite(min) || !Number.isFinite(max) || max <= min) return null;
2556
- return { min: min, max: max };
2557
- }
2558
- let priceBounds = null;
2559
- function computePriceBounds() {
2560
- let min = Infinity;
2561
- let max = -Infinity;
2562
- for (let i = 0; i < currentCandles.length; i++) {
2563
- const lo = currentLow[i];
2564
- const hi = currentHigh[i];
2565
- if (Number.isFinite(lo) && lo > 0 && lo < min) min = lo;
2566
- if (Number.isFinite(hi) && hi > max) max = hi;
2567
- }
2568
- if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || max <= min) {
2569
- priceBounds = null;
2570
- return;
2571
- }
2572
- // Uloszoomauksen rajat: alin naytettava hinta voi painua viimeistaan
2573
- // ~1/2 datan minimin alapuolelle, ylin ~2x datan maksimin —
2574
- // paneminen kayttaa tata 2x-bandia ja pysahtyy jaykkana sen
2575
- // reunaan (ei siis paase "lipsahtamaan" candleita nakyvasta
2576
- // kadottaen). Kokonaisvalille ei ole ylarajaa: pystyakselia saa
2577
- // zoomata ulos vapaasti.
2578
- priceBounds = { min: min, max: max, floor: min / 2, ceil: max * 2.0 };
2579
- }
2580
- function applyYRange(chart, min, max) {
2581
- if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) return false;
2582
- const ref = Math.max(Math.abs(min), Math.abs(max), 1e-12);
2583
- if (max - min < ref * 1e-9) return false;
2584
- if (currentPriceScale === 'log' && min <= 0) {
2585
- min = max > 0 ? max * 1e-6 : 1e-6;
2586
- if (max <= min) return false;
2587
- }
2588
- if (priceBounds) {
2589
- // Span-locked slide within the 2x zoom band: a pan that would
2590
- // cross the zoom-out limits stops as a rigid block instead of
2591
- // getting squashed (squashing reads as scaling halfway through
2592
- // a drag). Only a span wider than the band itself snaps to the
2593
- // full band. Scaling lives on the axis gutters alone.
2594
- if (currentPriceScale === 'log') {
2595
- const spanRatio = max / min;
2596
- if (spanRatio > priceBounds.ceil / priceBounds.floor) {
2597
- min = priceBounds.floor;
2598
- max = priceBounds.ceil;
2599
- } else {
2600
- if (max > priceBounds.ceil) {
2601
- const f = max / priceBounds.ceil;
2602
- min /= f; max /= f;
2603
- }
2604
- if (min < priceBounds.floor) {
2605
- const f = priceBounds.floor / min;
2606
- min *= f; max *= f;
2607
- }
2608
- }
2609
- } else {
2610
- const span = max - min;
2611
- if (span > priceBounds.ceil - priceBounds.floor) {
2612
- min = priceBounds.floor;
2613
- max = priceBounds.ceil;
2614
- } else {
2615
- if (max > priceBounds.ceil) { max = priceBounds.ceil; min = max - span; }
2616
- if (min < priceBounds.floor) { min = priceBounds.floor; max = min + span; }
2617
- }
2618
- }
2619
- if (!(max > min) || !Number.isFinite(min) || !Number.isFinite(max)) return false;
2620
- }
2621
- manualYRange = { min: min, max: max };
2622
- chart.setScale('y', { min: min, max: max });
2623
- return true;
2624
- }
2625
- function zoomYAt(chart, centerY, factor) {
2626
- const r = currentYRange(chart);
2627
- if (!r) return;
2628
- const span = r.max - r.min;
2629
- let ratio = (centerY - r.min) / span;
2630
- if (!Number.isFinite(ratio)) ratio = 0.5;
2631
- ratio = Math.max(0.05, Math.min(0.95, ratio));
2632
- const nextSpan = span * factor;
2633
- const nextMin = centerY - nextSpan * ratio;
2634
- applyYRange(chart, nextMin, nextMin + nextSpan);
2635
- }
2636
- function bindYAxisDrag(chart) {
2637
- let dragging = false;
2638
- let startClientY = 0;
2639
- let startRange = null;
2640
- const onMove = (e) => {
2641
- if (!dragging || !startRange) return;
2642
- e.preventDefault();
2643
- chart.root.style.cursor = 'ns-resize';
2644
- const deltaPx = e.clientY - startClientY;
2645
- if (!Number.isFinite(deltaPx) || deltaPx === 0) return;
2646
- const factor = Math.exp(deltaPx / 350);
2647
- const span = startRange.max - startRange.min;
2648
- const center = (startRange.min + startRange.max) / 2;
2649
- const nextSpan = span * factor;
2650
- applyYRange(chart, center - nextSpan / 2, center + nextSpan / 2);
2651
- };
2652
- const endDrag = () => {
2653
- if (!dragging) return;
2654
- dragging = false;
2655
- startRange = null;
2656
- chart.root.style.cursor = '';
2657
- window.removeEventListener('mousemove', onMove);
2658
- window.removeEventListener('mouseup', endDrag);
2659
- };
2660
- chart.root.addEventListener('mousedown', (e) => {
2661
- if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;
2662
- // capture phase so we pre-empt uPlot's own plot drag when in the y-zone
2663
- const rect = chart.root.getBoundingClientRect();
2664
- if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
2665
- if (chart !== priceChart || !inYAxisZone(chart, e.clientX)) return;
2666
- const range = currentYRange(chart);
2667
- if (!range) return;
2668
- e.preventDefault();
2669
- e.stopPropagation();
2670
- dragging = true;
2671
- startClientY = e.clientY;
2672
- startRange = range;
2673
- chart.root.style.cursor = 'ns-resize';
2674
- window.addEventListener('mousemove', onMove);
2675
- window.addEventListener('mouseup', endDrag, { once: true });
2676
- }, true);
2677
- }
2678
- // Time-axis drag scales the timeframe around its center (mirror of
2679
- // the price-axis drag): drag right to zoom out, left to zoom in.
2680
- // Synced across charts via syncXRange; capture phase pre-empts plot pan.
2681
- function bindXAxisDrag(chart) {
2682
- let dragging = false;
2683
- let startClientX = 0;
2684
- let startRange = null;
2685
- const onMove = (e) => {
2686
- if (!dragging || !startRange) return;
2687
- e.preventDefault();
2688
- chart.root.style.cursor = 'ew-resize';
2689
- const deltaPx = e.clientX - startClientX;
2690
- if (!Number.isFinite(deltaPx) || deltaPx === 0) return;
2691
- const factor = Math.exp(deltaPx / 350);
2692
- const span = startRange.max - startRange.min;
2693
- if (!Number.isFinite(span) || span <= 0) return;
2694
- const center = (startRange.min + startRange.max) / 2;
2695
- const nextSpan = span * factor;
2696
- syncXRange(center - nextSpan / 2, center + nextSpan / 2);
2697
- };
2698
- const endDrag = () => {
2699
- if (!dragging) return;
2700
- dragging = false;
2701
- startRange = null;
2702
- chart.root.style.cursor = '';
2703
- window.removeEventListener('mousemove', onMove);
2704
- window.removeEventListener('mouseup', endDrag);
2705
- };
2706
- chart.root.addEventListener('mousedown', (e) => {
2707
- if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;
2708
- // capture phase so we pre-empt the plot pan when in the x-zone
2709
- const rect = chart.root.getBoundingClientRect();
2710
- if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
2711
- if (!inXAxisZone(chart, e.clientY)) return;
2712
- const s = chart.scales.x || {};
2713
- const range = {
2714
- min: Number.isFinite(s.min) ? s.min : xMin,
2715
- max: Number.isFinite(s.max) ? s.max : xMax,
2716
- };
2717
- if (!Number.isFinite(range.min) || !Number.isFinite(range.max) || range.max <= range.min) return;
2718
- e.preventDefault();
2719
- e.stopPropagation();
2720
- dragging = true;
2721
- startClientX = e.clientX;
2722
- startRange = range;
2723
- chart.root.style.cursor = 'ew-resize';
2724
- window.addEventListener('mousemove', onMove);
2725
- window.addEventListener('mouseup', endDrag, { once: true });
2726
- }, true);
2727
- }
2728
- function bindYAxisReset(chart) {
2729
- chart.root.addEventListener('dblclick', (e) => {
2730
- if (chart !== priceChart) return;
2731
- manualYRange = null;
2732
- const vis = visiblePriceRange(chart);
2733
- if (vis) chart.setScale('y', { min: vis[0], max: vis[1] });
2734
- });
2735
- }
2736
- function refreshLegend() {
2737
- updateLegend(Math.max(0, currentCandles.length - 1));
2738
- }
2739
- function setControls() {
2740
- setActivePairMode(currentPairMode);
2741
- setActivePriceScale(currentPriceScale);
2742
- const ordersToggle = document.getElementById('orders-toggle');
2743
- if (ordersToggle) ordersToggle.checked = currentOrdersVisible;
2744
- const volumeToggleEl = document.getElementById('volume-toggle');
2745
- if (volumeToggleEl) volumeToggleEl.checked = currentVolumeVisible;
2746
- setActiveVolumeUnit();
2747
- markActiveAmaPreset();
2748
- document.getElementById('sma-toggle').checked = currentSmaEnabled;
2749
- document.getElementById('sma-period').value = String(currentSmaPeriod);
2750
- document.getElementById('ama-toggle').checked = currentAmaEnabled;
2751
- document.getElementById('ama-er').value = String(currentAmaErPeriod);
2752
- document.getElementById('ama-fast').value = currentAmaFastPeriod.toFixed(1);
2753
- document.getElementById('ama-slow').value = currentAmaSlowPeriod.toFixed(1);
2754
- document.getElementById('vwap-toggle').checked = currentVwapEnabled;
2755
- document.getElementById('vwap-bars').value = String(currentVwapBars);
2756
- document.getElementById('range-toggle').checked = currentRangeEnabled;
2757
- document.getElementById('range-scale-toggle').checked = currentRangeScaleEnabled;
2758
- document.getElementById('range-span').value = Number(currentRangeSpan).toFixed(2);
2759
- document.getElementById('range-span-val').textContent = Number(currentRangeSpan).toFixed(2) + 'x';
2760
- document.getElementById('range-grid-wrap').style.display = 'inline';
2761
- document.getElementById('ama-init-offset-toggle').checked = currentAmaInitOffsetEnabled;
2762
- document.getElementById('ama-init-offset').value = String(currentAmaInitOffset);
2763
- document.getElementById('ama-init-offset').disabled = !currentAmaInitOffsetEnabled;
2764
- document.getElementById('ama-init-offset-val').textContent = currentAmaInitOffset + '%';
2765
- setActiveTimeframe(currentTimeframe);
2766
- refreshSubtitle();
2767
- }
2768
- function rerender(keepRange = true) {
2769
- const oldRange = keepRange && priceChart ? priceChart.scales.x : null;
2770
- const needsRebuild = !priceChart || !volumeChart || lastRenderedPriceScale !== currentPriceScale;
2771
- if (needsRebuild) {
2772
- manualYRange = null;
2773
- priceMarkerLabel = null;
2774
- resetOverlayNodes();
2775
- volumeHoverTip = null;
2776
- if (priceEl) priceEl.innerHTML = '';
2777
- if (volumeEl) volumeEl.innerHTML = '';
2778
- priceChart = null;
2779
- volumeChart = null;
2780
- charts = [];
2781
- chartEventsBound = false;
2782
- }
2783
- const data = buildData();
2784
- // Dataset changed (timeframe switch, fresh candles): drop any manual
2785
- // price scale so auto-fit takes over again for the new data shape.
2786
- const candleKey = currentCandles.length
2787
- ? currentCandles[0].time + ':' + currentCandles[currentCandles.length - 1].time + ':' + currentCandles.length
2788
- : '';
2789
- if (candleKey !== lastCandleKey) {
2790
- lastCandleKey = candleKey;
2791
- manualYRange = null;
2792
- }
2793
- computePriceBounds();
2794
- if (needsRebuild) {
2795
- makeChart();
2796
- } else {
2797
- priceChart.setData(data.priceData, false);
2798
- volumeChart.setData(data.volumeData, false);
2799
- }
2800
- syncIndicatorSeriesVisibility();
2801
- if (!priceChart || !volumeChart) return;
2802
- if (!chartEventsBound) {
2803
- charts.forEach((chart) => {
2804
- bindWheelZoom(chart);
2805
- bindPan(chart);
2806
- bindXAxisDrag(chart);
2807
- if (chart === priceChart) {
2808
- bindYAxisDrag(chart);
2809
- bindYAxisReset(chart);
2810
- chart.root.addEventListener('mousemove', (e) => {
2811
- chart.root.style.cursor = inYAxisZone(chart, e.clientX) ? 'ns-resize' : (inXAxisZone(chart, e.clientY) ? 'ew-resize' : '');
2812
- });
2813
- // Cursor price tag: floating label next to the mouse
2814
- // showing the price under the cursor (price chart only).
2815
- let cursorPriceTag = null;
2816
- const ensureCursorPriceTag = () => {
2817
- if (!cursorPriceTag || cursorPriceTag.parentNode !== chart.root) {
2818
- if (cursorPriceTag && cursorPriceTag.parentNode) cursorPriceTag.parentNode.removeChild(cursorPriceTag);
2819
- cursorPriceTag = document.createElement('div');
2820
- cursorPriceTag.style.cssText = 'position:absolute;z-index:30;pointer-events:none;font:700 11px ui-monospace,SFMono-Regular,Menlo,monospace;line-height:16px;height:16px;padding:0 6px;border-radius:3px;color:#0b0f14;background:#e8eef5;white-space:nowrap;display:none;';
2821
- chart.root.appendChild(cursorPriceTag);
2822
- }
2823
- return cursorPriceTag;
2824
- };
2825
- chart.over.addEventListener('mousemove', (e) => {
2826
- const tag = ensureCursorPriceTag();
2827
- const rect = chart.root.getBoundingClientRect();
2828
- const overRect = chart.over.getBoundingClientRect();
2829
- const price = chart.posToVal(e.clientY - overRect.top, 'y');
2830
- if (!Number.isFinite(price)) { tag.style.display = 'none'; return; }
2831
- tag.style.display = 'block';
2832
- tag.textContent = fmtPriceLabel(price);
2833
- let x = e.clientX - rect.left + 14;
2834
- const y = e.clientY - rect.top - 8;
2835
- const maxX = rect.width - tag.offsetWidth - 6;
2836
- if (x > maxX) x = e.clientX - rect.left - tag.offsetWidth - 14;
2837
- tag.style.left = Math.max(2, x) + 'px';
2838
- tag.style.top = Math.max(2, y) + 'px';
2839
- });
2840
- chart.over.addEventListener('mouseleave', () => {
2841
- if (cursorPriceTag) cursorPriceTag.style.display = 'none';
2842
- });
2843
- }
2844
- chart.root.addEventListener('mousemove', () => {
2845
- if (chart.cursor.idx != null) updateLegend(chart.cursor.idx);
2846
- });
2847
- if (chart === volumeChart) {
2848
- chart.over.addEventListener('mousemove', () => showVolumeHover(chart));
2849
- chart.over.addEventListener('mouseleave', () => {
2850
- if (volumeHoverTip) volumeHoverTip.style.display = 'none';
2851
- });
2852
- }
2853
- chart.root.addEventListener('mouseleave', refreshLegend);
2854
- chart.root.addEventListener('mouseenter', () => chart.root.classList.add('is-hovered'));
2855
- chart.root.addEventListener('mouseleave', () => chart.root.classList.remove('is-hovered'));
2856
- });
2857
- chartEventsBound = true;
2858
- }
2859
- if (oldRange && Number.isFinite(oldRange.min) && Number.isFinite(oldRange.max)) {
2860
- const next = clampRange(oldRange.min, oldRange.max);
2861
- if (next) charts.forEach((chart) => chart.batch(() => chart.setScale('x', next)));
2862
- }
2863
- refreshLegend();
2864
- renderMarketPanel();
2865
- renderRangePanel();
2866
- renderVolumePanel();
2867
- saveState();
2868
- }
2869
-
2870
- setControls();
2871
- rerender(false);
2872
- document.querySelectorAll('.time-btn').forEach((btn) => {
2873
- btn.addEventListener('click', () => {
2874
- if (btn.disabled) return;
2875
- const label = btn.dataset.timeframe;
2876
- if (!label || label === currentTimeframe) return;
2877
- currentTimeframe = label;
2878
- setActiveTimeframe(label);
2879
- rerender(true);
2880
- });
2881
- });
2882
- const scaleToggle = document.getElementById('scale-toggle');
2883
- if (scaleToggle) {
2884
- scaleToggle.addEventListener('click', () => {
2885
- currentPriceScale = currentPriceScale === 'linear' ? 'log' : 'linear';
2886
- setActivePriceScale(currentPriceScale);
2887
- rerender(false);
2888
- });
2889
- }
2890
- const pairToggle = document.getElementById('pair-toggle');
2891
- if (pairToggle) {
2892
- pairToggle.addEventListener('click', () => {
2893
- currentPairMode = currentPairMode === 'inverse' ? 'normal' : 'inverse';
2894
- manualYRange = null;
2895
- lastOverlayKey = '';
2896
- setControls();
2897
- rerender(true);
2898
- padXRight();
2899
- });
2900
- }
2901
- const ordersToggle = document.getElementById('orders-toggle');
2902
- if (ordersToggle) {
2903
- ordersToggle.addEventListener('change', () => {
2904
- currentOrdersVisible = ordersToggle.checked;
2905
- lastOverlayKey = '';
2906
- if (!currentOrdersVisible && priceChart) hideOverlayNodes();
2907
- setControls();
2908
- saveState();
2909
- if (priceChart) {
2910
- positionReserveLine(priceChart);
2911
- positionOrderLines(priceChart);
2912
- }
2913
- renderMarketPanel();
2914
- });
2915
- }
2916
- // Volume toggle: hide the volume chart so flex yields the space to
2917
- // the price chart (larger). No rerender, resize only.
2918
- const applyVolumeVisibility = () => {
2919
- if (!volumeEl || !priceChart) return;
2920
- volumeEl.style.display = currentVolumeVisible ? '' : 'none';
2921
- requestAnimationFrame(() => {
2922
- if (!priceChart) return;
2923
- priceChart.setSize({ width: priceEl.clientWidth, height: priceEl.clientHeight });
2924
- if (currentVolumeVisible && volumeChart && volumeEl.clientWidth > 0) {
2925
- volumeChart.setSize({ width: volumeEl.clientWidth, height: volumeEl.clientHeight });
2926
- }
2927
- });
2928
- };
2929
- const volumeToggleInit = document.getElementById('volume-toggle');
2930
- if (volumeToggleInit) {
2931
- volumeToggleInit.checked = currentVolumeVisible;
2932
- volumeToggleInit.addEventListener('change', () => {
2933
- currentVolumeVisible = volumeToggleInit.checked;
2934
- saveState();
2935
- applyVolumeVisibility();
2936
- });
2937
- }
2938
- const volumeUnitToggle = document.getElementById('volume-unit-toggle');
2939
- if (volumeUnitToggle) {
2940
- volumeUnitToggle.addEventListener('click', () => toggleVolumeUnit());
2941
- }
2942
- const legendVolume = document.getElementById('legend-volume');
2943
- if (legendVolume) {
2944
- legendVolume.addEventListener('click', () => toggleVolumeUnit());
2945
- }
2946
- // Initial state on load (previously stored in localStorage)
2947
- applyVolumeVisibility();
2948
- document.querySelectorAll('.ama-preset-btn').forEach((b) => {
2949
- b.addEventListener('click', () => applyAmaPreset(b.dataset.amaPreset));
2950
- });
2951
-
2952
- const syncInputs = () => {
2953
- currentSmaEnabled = document.getElementById('sma-toggle').checked;
2954
- currentSmaPeriod = clamp(Math.round(Number(document.getElementById('sma-period').value) || 20), 1, 9999);
2955
- currentAmaEnabled = document.getElementById('ama-toggle').checked;
2956
- currentAmaErPeriod = clamp(Math.round(Number(document.getElementById('ama-er').value) || ${MARKET_ADAPTER.AMAS.AMA3.erPeriod}), 1, 999999);
2957
- currentAmaFastPeriod = Math.round(clamp(Number(document.getElementById('ama-fast').value) || Number(payload.amaDefaults?.fastPeriod || ${MARKET_ADAPTER.AMAS.AMA3.fastPeriod}), 0.1, 999999) * 10) / 10;
2958
- currentAmaSlowPeriod = Math.round(clamp(Number(document.getElementById('ama-slow').value) || Number(payload.amaDefaults?.slowPeriod || ${MARKET_ADAPTER.AMAS.AMA3.slowPeriod}), 0.1, 999999) * 10) / 10;
2959
- currentAmaInitOffsetEnabled = document.getElementById('ama-init-offset-toggle').checked;
2960
- currentAmaInitOffset = currentAmaInitOffsetEnabled ? snapInitOffset(document.getElementById('ama-init-offset').value) : 0;
2961
- document.getElementById('ama-init-offset').value = String(currentAmaInitOffset);
2962
- document.getElementById('ama-init-offset').disabled = !currentAmaInitOffsetEnabled;
2963
- document.getElementById('ama-init-offset-val').textContent = currentAmaInitOffset + '%';
2964
- currentVwapEnabled = document.getElementById('vwap-toggle').checked;
2965
- currentVwapBars = clamp(Math.round(Number(document.getElementById('vwap-bars').value) || 500), 24, 2000);
2966
- currentRangeEnabled = document.getElementById('range-toggle').checked;
2967
- currentRangeScaleEnabled = document.getElementById('range-scale-toggle').checked;
2968
- currentRangeSpan = Math.min(2, Math.max(1.2, Math.round((Number(document.getElementById('range-span').value) || 1.55) * 20) / 20));
2969
- const ordersEl = document.getElementById('orders-toggle');
2970
- if (ordersEl) currentOrdersVisible = ordersEl.checked;
2971
- setControls();
2972
- markActiveAmaPreset();
2973
- rerender(false);
2974
- };
2975
-
2976
- document.getElementById('sma-toggle').addEventListener('change', () => {
2977
- const nextEnabled = document.getElementById('sma-toggle').checked;
2978
- if (currentSmaEnabled === nextEnabled) return;
2979
- currentSmaEnabled = nextEnabled;
2980
- setControls();
2981
- if (!currentSmaEnabled) {
2982
- hideSmaSeriesImmediate();
2983
- return;
2984
- }
2985
- rerender(false);
2986
- });
2987
- document.getElementById('ama-toggle').addEventListener('change', () => {
2988
- const nextEnabled = document.getElementById('ama-toggle').checked;
2989
- if (currentAmaEnabled === nextEnabled) return;
2990
- currentAmaEnabled = nextEnabled;
2991
- setControls();
2992
- if (!currentAmaEnabled) {
2993
- hideAmaSeriesImmediate();
2994
- return;
2995
- }
2996
- rerender(false);
2997
- });
2998
- document.getElementById('vwap-toggle').addEventListener('change', () => {
2999
- const nextEnabled = document.getElementById('vwap-toggle').checked;
3000
- if (currentVwapEnabled === nextEnabled) return;
3001
- currentVwapEnabled = nextEnabled;
3002
- setControls();
3003
- if (!currentVwapEnabled) {
3004
- hideVwapSeriesImmediate();
3005
- return;
3006
- }
3007
- rerender(false);
3008
- });
3009
- document.getElementById('ama-init-offset-toggle').addEventListener('change', syncInputs);
3010
- document.getElementById('range-toggle').addEventListener('change', () => {
3011
- const nextEnabled = document.getElementById('range-toggle').checked;
3012
- if (currentRangeEnabled === nextEnabled) return;
3013
- currentRangeEnabled = nextEnabled;
3014
- setControls();
3015
- if (!currentRangeEnabled) {
3016
- hideRangeBandImmediate();
3017
- return;
3018
- }
3019
- rerender(false);
3020
- });
3021
- document.getElementById('range-scale-toggle').addEventListener('change', () => {
3022
- const nextEnabled = document.getElementById('range-scale-toggle').checked;
3023
- if (currentRangeScaleEnabled === nextEnabled) return;
3024
- currentRangeScaleEnabled = nextEnabled;
3025
- manualYRange = null;
3026
- setControls();
3027
- rerender(false);
3028
- });
3029
- ['sma-period', 'ama-er', 'ama-fast', 'ama-slow', 'vwap-bars'].forEach((id) => {
3030
- document.getElementById(id).addEventListener('change', syncInputs);
3031
- document.getElementById(id).addEventListener('blur', syncInputs);
3032
- });
3033
- ['ama-er'].forEach((id) => {
3034
- document.getElementById(id).addEventListener('input', syncInputs);
3035
- });
3036
- function makeStepper(id, step, lo, precision) {
3037
- const dec = document.getElementById(id + '-dec');
3038
- const inc = document.getElementById(id + '-inc');
3039
- if (!dec || !inc) return;
3040
- const input = document.getElementById(id);
3041
- function stepVal(dir) {
3042
- const val = parseFloat(input.value) || 0;
3043
- let next = dir < 0 ? Math.max(lo, val - step) : val + step;
3044
- if (precision === 0) next = Math.round(next);
3045
- else if (precision > 0) next = Math.round(next * Math.pow(10, precision)) / Math.pow(10, precision);
3046
- input.value = precision >= 0 ? next.toFixed(precision) : String(next);
3047
- syncInputs();
3048
- }
3049
- function addHold(el, dir) {
3050
- let timer = null;
3051
- function start() {
3052
- stepVal(dir);
3053
- timer = setTimeout(() => {
3054
- timer = setInterval(() => stepVal(dir), 100);
3055
- }, 300);
3056
- }
3057
- function stop() {
3058
- if (timer) { clearInterval(timer); clearTimeout(timer); timer = null; }
3059
- }
3060
- el.addEventListener('mousedown', start);
3061
- el.addEventListener('mouseup', stop);
3062
- el.addEventListener('mouseleave', stop);
3063
- }
3064
- addHold(dec, -1);
3065
- addHold(inc, 1);
3066
- }
3067
- makeStepper('sma-period', 1, 1, 0);
3068
- makeStepper('vwap-bars', 1, 24, 0);
3069
- makeStepper('ama-er', 10, 1, 0);
3070
- makeStepper('ama-fast', 0.1, 0.1, 1);
3071
- makeStepper('ama-slow', 1, 0.1, 1);
3072
- document.getElementById('ama-init-offset').addEventListener('input', () => {
3073
- const input = document.getElementById('ama-init-offset');
3074
- const snapped = snapInitOffset(input.value);
3075
- if (String(snapped) !== String(input.value)) input.value = String(snapped);
3076
- document.getElementById('ama-init-offset-val').textContent = snapped + '%';
3077
- syncInputs();
3078
- });
3079
- document.getElementById('range-span').addEventListener('input', () => {
3080
- const input = document.getElementById('range-span');
3081
- document.getElementById('range-span-val').textContent = Number(input.value).toFixed(2) + 'x';
3082
- syncInputs();
3083
- });
3084
-
3085
- // Room to the right past the last bar (~12%): for the market panel
3086
- // and future candles. Applied at init and on pair flip; user
3087
- // zoom/pan never trigger it, so it does not fight the user zoom.
3088
- function padXRight() {
3089
- if (!priceChart || !currentCandles.length) return;
3090
- const first = currentCandles[0]?.time;
3091
- const last = currentCandles[currentCandles.length - 1]?.time;
3092
- if (!Number.isFinite(first) || !Number.isFinite(last) || last <= first) return;
3093
- const span = last - first;
3094
- syncXRange(first - span * 0.02, last + span * 0.12);
3095
- }
3096
- // Market panel top-right: SELL / Market / BUY with distance-to-market
3097
- // %. Pair-aware (same display levels as the overlay). Static per
3098
- // generation, so drawn once (no draw hook); refreshed on pair flip
3099
- // via rerender. Hidden while the Orders overlay is unchecked — the
3100
- // BUY/SELL rows are overlay data, so they go away with it.
3101
- function renderMarketPanel() {
3102
- if (!priceChart) return;
3103
- let panel = document.getElementById('mkt-panel');
3104
- if (!panel) {
3105
- panel = document.createElement('div');
3106
- panel.id = 'mkt-panel';
3107
- panel.style.cssText = 'position:absolute;z-index:26;top:10px;right:88px;pointer-events:none;font:600 14px ui-monospace,SFMono-Regular,Menlo,monospace;line-height:1.6;padding:8px 12px;border-radius:8px;background:rgba(13,17,23,0.85);border:1px solid #263241;white-space:nowrap;text-align:right;';
3108
- priceChart.root.appendChild(panel);
3109
- }
3110
- if (!currentOrdersVisible && (hasOrders || hasBounds)) { panel.style.display = 'none'; return; }
3111
- panel.style.display = 'block';
3112
- const last = currentCandles[currentCandles.length - 1];
3113
- const mkt = last ? last.close : NaN;
3114
- const { buys, sells } = getDisplayOrders();
3115
- let html = '';
3116
- if (sells.length && Number.isFinite(mkt)) {
3117
- const s = Math.min(...sells);
3118
- const p = (s - mkt) / mkt * 100;
3119
- html += '<div style="color:#ef5350">SELL ' + fmtPriceLabel(s) + ' ' + (p >= 0 ? '+' : '') + p.toFixed(1) + '%</div>';
3120
- }
3121
- html += '<div style="color:#e8eef5">Market ' + (Number.isFinite(mkt) ? fmtPriceLabel(mkt) : '-') + '</div>';
3122
- if (buys.length && Number.isFinite(mkt)) {
3123
- const b = Math.max(...buys);
3124
- const p = (b - mkt) / mkt * 100;
3125
- html += '<div style="color:#26a69a">BUY ' + fmtPriceLabel(b) + ' ' + (p >= 0 ? '+' : '') + p.toFixed(1) + '%</div>';
3126
- }
3127
- panel.innerHTML = html;
3128
- }
3129
- // Range panel bottom-right: visible-window candle High (red) /
3130
- // Low (green) — sell-side red on top, buy-side green below, mirroring
3131
- // the top-right market badge. Volume max lives in its own badge on
3132
- // the volume chart below. Slightly smaller type than the top-right market badge.
3133
- // Pair-aware via currentCandles (already inverted in B/A view).
3134
- // Refreshed on rerender and on x zoom/pan through the setScale hooks.
3135
- function visibleCandleStats() {
3136
- if (!currentCandles.length) return null;
3137
- let minX = NaN;
3138
- let maxX = NaN;
3139
- if (priceChart) {
3140
- const xs = priceChart.scales.x || {};
3141
- if (Number.isFinite(xs.min)) minX = xs.min;
3142
- if (Number.isFinite(xs.max)) maxX = xs.max;
3143
- }
3144
- if (!Number.isFinite(minX)) minX = currentCandles[0].time;
3145
- if (!Number.isFinite(maxX)) maxX = currentCandles[currentCandles.length - 1].time;
3146
- const times = currentCandles.map((c) => c.time);
3147
- const start = Math.max(0, lowerBound(times, minX) - 1);
3148
- const end = Math.min(times.length, lowerBound(times, maxX) + 2);
3149
- let hi = -Infinity;
3150
- let lo = Infinity;
3151
- let vol = 0;
3152
- for (let i = start; i < end; i++) {
3153
- const c = currentCandles[i];
3154
- if (!c) continue;
3155
- if (Number.isFinite(c.high) && c.high > hi) hi = c.high;
3156
- if (Number.isFinite(c.low) && c.low < lo) lo = c.low;
3157
- const dv = getDisplayVolume(c);
3158
- if (Number.isFinite(dv) && dv > vol) vol = dv;
3159
- }
3160
- if (!Number.isFinite(hi) || !Number.isFinite(lo)) return null;
3161
- return { hi, lo, vol };
3162
- }
3163
- function renderRangePanel() {
3164
- if (!priceChart) return;
3165
- let panel = document.getElementById('range-panel');
3166
- if (!panel) {
3167
- panel = document.createElement('div');
3168
- panel.id = 'range-panel';
3169
- panel.style.cssText = 'position:absolute;z-index:26;bottom:10px;right:88px;pointer-events:none;font:600 12px ui-monospace,SFMono-Regular,Menlo,monospace;line-height:1.6;padding:6px 10px;border-radius:8px;background:rgba(13,17,23,0.85);border:1px solid #263241;white-space:nowrap;text-align:right;';
3170
- priceChart.root.appendChild(panel);
3171
- }
3172
- const stats = visibleCandleStats();
3173
- if (!stats) { panel.style.display = 'none'; return; }
3174
- panel.style.display = 'block';
3175
- panel.innerHTML = '<div style="color:#ef5350">H ' + fmtPriceLabel(stats.hi) + '</div>'
3176
- + '<div style="color:#26a69a">L ' + fmtPriceLabel(stats.lo) + '</div>';
3177
- }
3178
- // Volume badge top-right on the volume chart: max volume of the
3179
- // visible window only. Same small type as the range panel. Lives on
3180
- // the volume root, so hiding the volume chart hides the badge too.
3181
- function renderVolumePanel() {
3182
- if (!volumeChart) return;
3183
- let panel = document.getElementById('vol-panel');
3184
- if (!panel) {
3185
- panel = document.createElement('div');
3186
- panel.id = 'vol-panel';
3187
- panel.style.cssText = 'position:absolute;z-index:26;top:10px;right:88px;pointer-events:auto;font:600 12px ui-monospace,SFMono-Regular,Menlo,monospace;line-height:1.6;padding:6px 10px;border-radius:8px;background:rgba(13,17,23,0.85);border:1px solid #263241;white-space:nowrap;text-align:right;';
3188
- panel.addEventListener('click', () => toggleVolumeUnit());
3189
- volumeChart.root.appendChild(panel);
3190
- }
3191
- panel.style.cursor = payload.volumeIsCount ? 'default' : 'pointer';
3192
- panel.title = payload.volumeIsCount
3193
- ? 'Volume: feed publish count per bucket'
3194
- : 'Volume units — click to switch base/quote';
3195
- const stats = visibleCandleStats();
3196
- if (!stats) { panel.style.display = 'none'; return; }
3197
- panel.style.display = 'block';
3198
- panel.innerHTML = '<div style="color:#e8eef5">max ' + fmtVolumeWithSym(stats.vol) + '</div>';
3199
- }
3200
- function scheduleStatPanels() {
3201
- if (rangePanelRaf) return;
3202
- rangePanelRaf = requestAnimationFrame(() => {
3203
- rangePanelRaf = 0;
3204
- renderRangePanel();
3205
- renderVolumePanel();
3206
- });
3207
- }
3208
- // uPlot does not recompute an auto Y scale when X moves via
3209
- // setScale('x') — the scale range fns only run on init/data
3210
- // change. Refit Y to the visible window after every timeframe
3211
- // move so candles/volume follow the pan/zoom instead of getting
3212
- // stuck outside the view. A user-locked price range (axis
3213
- // wheel/drag → manualYRange) is respected; double-click the
3214
- // price axis to return to autofit. y-keyed setScale calls never
3215
- // schedule a refit, so this cannot loop with itself.
3216
- function yRangeDirty(u, vis) {
3217
- const s = u.scales.y || {};
3218
- if (!Number.isFinite(s.min) || !Number.isFinite(s.max)) return true;
3219
- const span = Math.max(1e-12, Math.abs(vis[1] - vis[0]));
3220
- return Math.abs(s.min - vis[0]) / span > 1e-9 || Math.abs(s.max - vis[1]) / span > 1e-9;
3221
- }
3222
- function scheduleYRefit() {
3223
- if (yRefitRaf) return;
3224
- yRefitRaf = requestAnimationFrame(() => {
3225
- yRefitRaf = 0;
3226
- if (priceChart && !manualYRange) {
3227
- const vis = visiblePriceRange(priceChart);
3228
- if (vis && yRangeDirty(priceChart, vis)) priceChart.setScale('y', { min: vis[0], max: vis[1] });
3229
- }
3230
- if (volumeChart) {
3231
- const vvis = visibleVolumeRange(volumeChart);
3232
- if (vvis && yRangeDirty(volumeChart, vvis)) volumeChart.setScale('y', { min: vvis[0], max: vvis[1] });
3233
- }
3234
- });
3235
- }
3236
- padXRight();
3237
- renderMarketPanel();
3238
- renderRangePanel();
3239
- renderVolumePanel();
3240
-
3241
- window.addEventListener('resize', () => {
3242
- if (!charts.length) return;
3243
- charts.forEach((chart) => {
3244
- const el = chart === priceChart ? priceEl : volumeEl;
3245
- if (el.clientWidth <= 0 || el.clientHeight <= 0) return;
3246
- chart.setSize({ width: el.clientWidth, height: el.clientHeight });
3247
- });
3248
- });
3249
-
3250
- window.addEventListener('keydown', (e) => {
3251
- const tag = (document.activeElement && document.activeElement.tagName) || '';
3252
- if (tag === 'INPUT' || tag === 'TEXTAREA') return;
3253
- if ((e.ctrlKey || e.metaKey) && e.key === '0' && charts.length) {
3254
- const first = currentCandles[0]?.time;
3255
- const last = currentCandles[currentCandles.length - 1]?.time;
3256
- if (Number.isFinite(first) && Number.isFinite(last)) syncXRange(first, last);
3257
- }
3258
- });
3259
-
3260
- ${zoomResetScript()}
3261
- })();
3262
- </script>
3263
- </body>
3264
- </html>`;
3265
- }
3266
-
3267
- export { generateHTML, normalizeCandle, loadMarketProfiles, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY }
3268
-