dexbot 1.6.15 → 1.6.16

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 (102) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +4 -4
  3. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  4. package/claw/modules/chain_queries.ts +3 -3
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  10. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  12. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  13. package/dist/analysis/bot_key_utils.js +9 -7
  14. package/dist/analysis/chart_utils.d.ts +9 -2
  15. package/dist/analysis/chart_utils.js +51 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +19 -5
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  19. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  20. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  21. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  22. package/dist/dexbot.js +89 -138
  23. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  24. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  25. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  26. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  27. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  28. package/dist/market_adapter/inputs/window_cache.js +53 -17
  29. package/dist/market_adapter/lp_chart_core.js +1 -0
  30. package/dist/market_adapter/utils/chain.js +4 -3
  31. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  32. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  33. package/dist/modules/account_bots.d.ts +37 -3
  34. package/dist/modules/account_bots.js +77 -37
  35. package/dist/modules/account_orders.d.ts +4 -1
  36. package/dist/modules/account_orders.js +4 -1
  37. package/dist/modules/bitshares-native/resolvers.js +3 -3
  38. package/dist/modules/bitshares_client.d.ts +12 -10
  39. package/dist/modules/bitshares_client.js +12 -10
  40. package/dist/modules/bot_settings.js +3 -3
  41. package/dist/modules/chain_keys.d.ts +5 -1
  42. package/dist/modules/chain_keys.js +5 -1
  43. package/dist/modules/chain_orders.d.ts +6 -2
  44. package/dist/modules/chain_orders.js +6 -2
  45. package/dist/modules/constants.d.ts +5 -0
  46. package/dist/modules/constants.js +7 -1
  47. package/dist/modules/dexbot_class.d.ts +3 -1
  48. package/dist/modules/dexbot_class.js +3 -1
  49. package/dist/modules/graceful_shutdown.d.ts +6 -2
  50. package/dist/modules/graceful_shutdown.js +6 -2
  51. package/dist/modules/launcher/bot_supervisor.js +4 -0
  52. package/dist/modules/launcher/launch_modes.js +6 -3
  53. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  54. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  55. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  56. package/dist/modules/launcher/runtime_mode.js +223 -0
  57. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  58. package/dist/modules/market_adapter_whitelist.js +8 -0
  59. package/dist/modules/order/accounting.d.ts +15 -1
  60. package/dist/modules/order/accounting.js +15 -1
  61. package/dist/modules/order/async_lock.d.ts +9 -3
  62. package/dist/modules/order/async_lock.js +9 -3
  63. package/dist/modules/order/export.d.ts +0 -5
  64. package/dist/modules/order/export.js +0 -5
  65. package/dist/modules/order/format.d.ts +6 -4
  66. package/dist/modules/order/format.js +6 -4
  67. package/dist/modules/order/grid.d.ts +29 -18
  68. package/dist/modules/order/grid.js +29 -18
  69. package/dist/modules/order/index.d.ts +1 -1
  70. package/dist/modules/order/index.js +1 -1
  71. package/dist/modules/order/logger_state.d.ts +1 -1
  72. package/dist/modules/order/logger_state.js +1 -1
  73. package/dist/modules/order/sync_engine.d.ts +26 -11
  74. package/dist/modules/order/sync_engine.js +26 -11
  75. package/dist/modules/order/utils/math.d.ts +59 -21
  76. package/dist/modules/order/utils/math.js +59 -21
  77. package/dist/modules/order/utils/order.d.ts +64 -20
  78. package/dist/modules/order/utils/order.js +64 -20
  79. package/dist/modules/order/utils/system.d.ts +41 -11
  80. package/dist/modules/order/utils/system.js +41 -11
  81. package/dist/modules/order/utils/validate.d.ts +5 -2
  82. package/dist/modules/order/utils/validate.js +5 -2
  83. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  84. package/dist/modules/utils/asset_symbols.js +5 -5
  85. package/dist/modules/utils/errors.d.ts +2 -1
  86. package/dist/modules/utils/errors.js +2 -1
  87. package/dist/scripts/rich_list.d.ts +32 -0
  88. package/dist/scripts/rich_list.js +16 -8
  89. package/dist/unlock.js +49 -18
  90. package/docs/BITSHARES_ONBOARDING.md +7 -0
  91. package/docs/COW_INVARIANTS.md +1 -1
  92. package/docs/DEXBOT_COMPARISON.md +5 -5
  93. package/docs/EVOLUTION.md +8 -7
  94. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  95. package/docs/GRID_RECALCULATION.md +18 -6
  96. package/docs/LIFECYCLE.md +8 -8
  97. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +4 -4
  98. package/docs/README.md +1 -1
  99. package/docs/WORKFLOW.md +5 -5
  100. package/market_adapter/README.md +10 -3
  101. package/package.json +3 -1
  102. package/tests/README.md +29 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,32 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.16] - 2026-10-18 - Monolithic Per-Bot Control Routing, Candle-Cache Orientation Sharing, Chart Redraw Performance, Adapter Whitelist Sync, `dexbot rich` Symbol Canonicalization
6
+
7
+ ### 2026-10-18
8
+
9
+ - **Fix(launcher)**: make per-bot control work under the monolithic runtime — `dexbot reload|restart|stop <bot>` skipped the monolithic branch (guarded by `!target`) and fell through to the isolated supervisor socket, which does not exist in that mode, so the command failed with a misleading "No supervisor socket found" while the runtime was up; `status <bot>` silently dropped the target and `delete <bot>` tore down the whole isolated supervisor. Every control now goes through one pure resolver, `resolveControlRouting` (`modules/launcher/monolithic_runtime.ts`): whole-runtime forms canonicalize to `*-all`/`delete`, a bot target passes through to the isolated supervisor, a live monolithic runtime folds it into the whole-runtime action with a notice (validating the name first so a typo cannot reload every bot), `delete <bot>` is rejected and `status <bot>` is validated then ignored, and the supervisor's `delete` refuses a bot target as defence in depth. Runtime detection is centralized in the new `modules/launcher/runtime_mode.ts` (monolithic → isolated → pm2 → none), shared by `dexbot status` and the new mode-aware `dexbot help` so the two cannot disagree; a `pm2.pid` fast path keeps the help/typo path free of a pm2 probe. Behavioral note: unknown bot names are now rejected on folded paths, while the isolated pass-through still lets the supervisor validate. Covered by `tests/test_control_routing.ts`, `tests/test_runtime_mode.ts` and `tests/test_unlock_control_output.ts`.
10
+
11
+ - **Fix(account_bots)**: keep the adapter whitelist in sync on rename and copy — renaming a bot without touching menu 6 never armed the adapter commit hook (the gate was staged/new/copy), so the whitelist entry stayed under the old key and the renamed bot silently reverted to all-off defaults. The positional `baseIndex` inference is replaced by an explicit `BotEditorMode` (`'new'|'modify'|'copy'`) with the commit plan resolved up front, and the I/O-free `resolveAdapterCommitPlan`/`sameAdapterFlags` helpers are extracted so copy/rename semantics are unit-tested, including a regression that a copy never moves (and so never deletes) the source entry. The generic `setWhitelistFlags` overwrites an occupied key while `renameWhitelistEntry` refuses one, because the setter is used by new/modify/copy where claiming a stale entry is expected, whereas a move deletes the source and must not clobber a live occupant. Behavioral impact: modify-renames now move the whitelist entry and copies duplicate the source flags without touching it.
12
+
13
+ - **Refactor(account_bots)**: collapse save output into one green line — the adapter-flag commit hook logged its own green success line before `main()` logged "Added bot ...", so a single save produced two status lines. `commitAdapter` now returns a status (`'saved'`/`'unchanged'`/`'failed'`) instead of printing on success, and the adapter note is folded into the Add/Copy status lines. Copy semantics are fixed in the same hook: `promptBotData` runs for copies with `baseIndex !== index`, but the hook treated the new key like a rename and moved (deleting) the source bot's whitelist entry; the rename is now gated on `baseIndex === index`, comparisons and writes use `newKey` for copies, and a copy commits even without a menu-6 edit so the flags the editor showed are duplicated. Modify keeps its multi-line guidance and only appends "Adapter flags saved." when a write happened.
14
+
15
+ - **Feat(cache)**: share the candle cache across pair orientations — the LP, order-book and feed candle caches keyed on the typed asset order, so a pair and its inverse were two unrelated cache families holding reciprocal data and each re-queried Kibana independently. All three now store under one canonical orientation (lower asset id is leg A) and translate at the cache boundary, so querying one side reuses the other's shards. New `market_adapter/utils/pair_orientation.ts` holds the single definition of canonical ordering, the pair folder slug, same/swapped asset matching, the legacy sibling path and candle inversion (volume approximated as base × close, matching the TV chart's inverse view); `window_cache` gains a generic inverse-shard fallback that reads an absent canonical month from the opposite-orientation family, transforms and folds it back on flush, so an existing inverse cache is migrated instead of re-fetched. LP/book/feed fetchers canonicalize storage and fetch then invert the result back to the requested orientation, and the whole-history exporters rebuild the requested orientation from canonical shards. Behavioral impact: existing inverse-orientation folders are reused once and migrated; inverse volume remains a documented approximation; no runtime bot candle path is affected. Covered by `tests/test_candle_cache_inverse_sharing.ts`.
16
+
17
+ - **Fix(profiles)**: match and write market profiles orientation-insensitively — with the candle cache now canonical, a profile fitted from an assembled data file can be keyed on either side of the pair, yet `resolveAmaConfig` and the TradingView chart's `findMarketProfile` still required the bot's typed order and silently fell back to builtin AMA defaults, while the optimizer could accumulate one entry per orientation. Both lookups now accept either order, and the optimizer writes the canonical pair/key and replaces a same-pair entry in either orientation rather than duplicating it, leaving the lookup tolerance as a safety net for old entries. Covered by `tests/test_market_profile_orientation.ts`.
18
+
19
+ - **Fix(chart)**: prevent a log-axis hang and clip per-bar draw hooks to the viewport — uPlot 1.6.32's built-in log-scale splits generator can loop forever on a narrow price range (its tick step is reassigned to an intermediate value missing from the nice-number cache, so rounding collapses it to 0 and the tick array grows until "Invalid array length"/OOM); scroll-wheel zooming the dynamic-weight chart triggered this and blocked the tab for tens of seconds. A shared `logAxisSplits` replaces it on every `distr: 3` price axis (dynamic-weight, volatility, regime, kalman, derivative, lp) and only emits 1/2/5 × 10^d values inside `[min, max]`, yielding no ticks for invalid/empty ranges instead of hanging. `makePctFillHook` is clipped to the visible bar window via the shared `visibleBarRange`/`VIEWPORT_CLIP_SCRIPT`, and signal-background segments that cannot intersect the viewport are culled; runs reaching the last real bar still extend to the right edge. Zoomed-in redraws drop ~37–74% while full-range and future-padding renders stay pixel-identical. Behavioral impact: log price axes now show 1/2/5 × 10^d gridlines instead of uPlot's default (including 2.5). Covered by `tests/test_chart_log_axis_splits.ts`.
20
+
21
+ - **Fix(chart)**: clip the TradingView range-band hook to visible bars — `drawRangeBand` walked every bar on every redraw (`for i < xs.length`), calling `valToPos` four times per bar and building polylines for the whole series, so zooming in cost the same as the full-range view and on large generated charts (tens of thousands of candles) enabling the Range band roughly doubled redraw work. It now walks `u.series[0].idxs` (padded one bar each side so segments crossing the viewport edge stay connected), matching the sibling `drawSimBand`/`drawSimResets` hooks; full-range output is unchanged while per-redraw canvas work scales with the viewport (measured on a ~26k-bar page in Firefox: band `ctx.lineTo` drops from ~152,800 at full range to ~1,800 when zoomed to 300 bars, ~1.2%). Verified by the new Playwright suite.
22
+
23
+ - **Feat(tradingview)**: move the volume controls beside the pair switcher — the Volume toggle and base/quote unit badge move from the right-hand toolbar group to the leftmost group, immediately before the pair orientation switcher, since volume units derive from the orientation and the dependency should be visible rather than hidden at the far end of the row. Markup only: element IDs and handlers are unchanged, so volume visibility, unit switching and persisted chart state are unaffected.
24
+
25
+ - **Test(chart)**: add a Firefox Playwright suite for generated chart pages — the generated pages are canvas-heavy draw hooks that only run in a browser, so the Node runner cannot exercise them. `tests/playwright/tv_chart_perf.spec.mjs` loads a real exported page and asserts it loads without console/page errors with uPlot initialized, that range-band redraw cost scales with the visible window (counting `CanvasRenderingContext2D.lineTo` band-on vs band-off, deterministic, no wall-clock timing), and that the band still spans the plot when zoomed in (pixel diff with a pinned y-range). The uPlot interception is generic and `TV_CHART_HTML=<path>` runs the load check against any already-generated page (TV-only assertions skip without a Range toggle), a missing/stale `dist/` is reported instead of silently testing old code, and Playwright stays out of the dependency tree (`npm run test:playwright` resolves a global install via `NODE_PATH`).
26
+
27
+ - **Fix(rich)**: canonicalize asset symbols before chain lookup — `dexbot rich` passed CLI symbols straight into the case-sensitive `lookup_asset_symbols`, so any lowercase symbol resolved to null and the command reported "asset not found" even though the asset exists, while every other chain-facing caller already ran symbols through `modules/utils/asset_symbols`. `lookupSymbols` now normalizes so both the initial lookup and the legacy `bit*` alias retry reach the chain uppercase, request/alias reporting keeps the caller's original spelling, and `main()` is guarded so tests can import it without opening a websocket. Also corrects the stale "nodes accept lowercase lookups" comments that caused the gap. Behavioral impact: `dexbot rich <asset>` resolves symbols case-insensitively (asset object ids unchanged). Covered by `tests/test_rich_list_symbol_normalization.ts`.
28
+
29
+ - **Docs**: fix stale references in analysis comments and the market-adapter module map (bot-fitting/backtest and bot-key AMA comments now cite symbols instead of drifted `file.ts:NN` ranges, a stray drifted spread-gap comment is dropped, and `cli_args.ts`/`utils/pair_orientation.ts` are added to the documented layout); reconcile per-module headers, export inventories, TOCs and JSDoc with the current code across `constants`, `chain_keys`, `graceful_shutdown`, `bitshares_client`, `account_bots`, `account_orders`, `chain_orders`, `order/*`, `utils/errors` and `dexbot_class` (dangling moved-file references removed); and sync the linked docs with current defaults and code references (`LIFECYCLE`, `COW_INVARIANTS`, `FUND_MOVEMENT` line links; the real AMA resolution order in `GRID_RECALCULATION`; fitted built-in preset values in the market-adapter README; the shipped `weightDistribution` default in the tuning cheat sheet; superseded plan sources marked deleted in the order-engine retrospective). Docs/comments only; `npx tsc --noEmit` clean.
30
+
5
31
  ## [1.6.15] - 2026-10-16 - Spread-Correction Resilience, Credit Renewal Free-Collateral Top-Up, Price-vs-Amount Level Identity, TradingView Chart Fixes & Data-Age Badge, `dexbot rich`, Parallel Test Runner
6
32
 
7
33
  ### 2026-10-16
package/README.md CHANGED
@@ -314,14 +314,14 @@ Defaults in [`modules/constants.ts`](modules/constants.ts) are overridable at gl
314
314
 
315
315
  ## 🎯 Zero-Dependency Process Management
316
316
 
317
- `dexbot start` is the recommended production runtime (global install). Repo-root users can run `./unlock` instead. It runs the selected bot set as one monolithic bot process, with the credential daemon and market adapter in separate helper processes. Monolithic start/stop/reload/restart controls apply to the whole runtime, not to individual bots.
317
+ `dexbot start` is the recommended production runtime (global install). Repo-root users can run `./unlock` instead. It runs the selected bot set as one monolithic bot process, with the credential daemon and market adapter in separate helper processes. Monolithic start/stop/reload/restart controls apply to the whole runtime, not to individual bots: a bot argument (e.g. `dexbot reload <bot>`) is validated and then folds into the whole-runtime action with a notice. Per-bot control needs `--isolated` (one supervisor process per bot, then `stop`/`reload`/`restart <bot>` acts on just that bot). `delete` and `status` are whole-runtime only. `dexbot help` detects which runtime is up (monolithic, isolated, or PM2) and lists the controls for that mode.
318
318
 
319
319
  ```bash
320
320
  dexbot start/stop # Stop/start the monolithic runtime
321
321
  dexbot start --dryrun # Dry-run (no transactions broadcast)
322
- dexbot reload # Reload the runtime (leaves credential daemon untouched)
323
- dexbot restart # Restart the runtime (re-unlocks credential daemon)
324
- dexbot delete # Shut down and clean up
322
+ dexbot reload [<bot>] # Reload (monolithic: whole runtime; isolated: one bot)
323
+ dexbot restart [<bot>] # Restart (re-unlocks credential daemon)
324
+ dexbot delete # Shut down and clean up (whole runtime)
325
325
  ```
326
326
 
327
327
  First-run details and common mistakes are covered in the [BitShares Onboarding Tutorial](docs/BITSHARES_ONBOARDING.md).
@@ -70,7 +70,8 @@ This is the empty gap between the best buy and best sell rails.
70
70
 
71
71
  This controls how size is distributed across the ladder.
72
72
 
73
- - `0.5` is the neutral baseline
73
+ - `0.5` is the neutral baseline; `1.0` is the shipped default (mountain)
74
+ - the scale runs from `-1` (super-valley) to `2` (super-mountain)
74
75
  - values above `0.5` concentrate more size near the market-adjacent orders
75
76
  - values below `0.5` flatten the ladder
76
77
 
@@ -211,7 +212,7 @@ For a conservative starting point:
211
212
  - `incrementPercent: 0.5`
212
213
  - `targetSpreadPercent: 2.0`
213
214
  - `coreOrders: 20 / 20`
214
- - `weightDistribution: 0.5 / 0.5`
215
+ - `weightDistribution: 1.0 / 1.0` — the shipped default (mountain); flatten toward `0.5 / 0.5` only if you deliberately want a flatter ladder
215
216
  - `minPrice` and `maxPrice`: as narrow as the expected drift allows, not blindly `3x`
216
217
 
217
218
  For a more competitive market:
@@ -41,9 +41,9 @@ async function getDynamicGlobalProperties() {
41
41
  }
42
42
 
43
43
  async function getAsset(symbolOrId: any) {
44
- // Symbols arrive from a user-supplied `pair: "BASE/QUOTE"` option; BitShares
45
- // answers lowercase lookups without error, so canonicalize before the id
46
- // test and both lookup paths.
44
+ // Symbols arrive from a user-supplied `pair: "BASE/QUOTE"` option; the chain
45
+ // lookup is case-sensitive, so canonicalize before the id test and both
46
+ // lookup paths.
47
47
  const ref = normalizeAssetRef(symbolOrId);
48
48
  if (/^1\.3\.\d+$/.test(ref)) {
49
49
  const assets = await dbCall('get_assets', [[ref]]);
package/claw/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.15",
3
+ "version": "1.6.16",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
@@ -2,7 +2,7 @@
2
2
  "id": "bitshares-claw",
3
3
  "name": "BitShares Claw",
4
4
  "description": "Native BitShares and DEXBot2 tools from the DEXBot2 claw integration",
5
- "version": "1.6.15",
5
+ "version": "1.6.16",
6
6
  "skills": [
7
7
  "skills"
8
8
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bitshares-claw-openclaw-plugin",
3
3
  "private": true,
4
- "version": "1.6.15",
4
+ "version": "1.6.16",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -26,6 +26,7 @@ import { MARKET_ADAPTER } from '../../modules/constants.js';
26
26
  import { getErrorMessage } from '../../modules/utils/errors.js';
27
27
  import { writeJsonAtomic } from '../../market_adapter/utils/atomic_write.js';
28
28
  import { loadLpSeriesFromBasePath } from '../../market_adapter/utils/data_discovery.js';
29
+ import { canonicalPair, invertCandleSeries } from '../../market_adapter/utils/pair_orientation.js';
29
30
  import { normalizePoolId } from '../../market_adapter/utils/chain.js';
30
31
  import { fetchCandlesSequentially, outputPath, } from '../../market_adapter/inputs/fetch_lp_data.js';
31
32
  const HOURS_3Y = 3 * 365 * 24; // 26280
@@ -180,7 +181,13 @@ async function main() {
180
181
  // snapshot (same meta shape as fetch_lp_data's export). Deriving it from
181
182
  // the assembled shards means a narrow re-run can never shrink the file.
182
183
  const assembled = loadLpSeriesFromBasePath(outPath);
183
- const exportCandles = (assembled && assembled.candles.length > 0 ? assembled.candles : candles);
184
+ // Shards are canonical; the export is the requested orientation.
185
+ const assembledCandles = assembled && assembled.candles.length > 0
186
+ ? (canonicalPair(assetA, assetB).flipped
187
+ ? invertCandleSeries(assembled.candles, { volume: 'scale' })
188
+ : assembled.candles)
189
+ : null;
190
+ const exportCandles = (assembledCandles ?? candles);
184
191
  const firstTs = new Date(exportCandles[0][0]).toISOString();
185
192
  const lastTs = new Date(exportCandles[exportCandles.length - 1][0]).toISOString();
186
193
  console.log(` Received: ${exportCandles.length} candles (${firstTs} → ${lastTs})`);
@@ -1,3 +1,41 @@
1
+ interface DataMeta {
2
+ intervalSeconds?: unknown;
3
+ pool?: unknown;
4
+ fetchedAt?: unknown;
5
+ assetA?: {
6
+ symbol?: unknown;
7
+ id?: unknown;
8
+ };
9
+ assetB?: {
10
+ symbol?: unknown;
11
+ id?: unknown;
12
+ };
13
+ [key: string]: unknown;
14
+ }
15
+ interface AmaArea {
16
+ maxDist: number;
17
+ total: number;
18
+ above: number;
19
+ below: number;
20
+ [key: string]: unknown;
21
+ }
22
+ interface SearchEntry {
23
+ er: number;
24
+ fast: number;
25
+ slow: number;
26
+ area: AmaArea;
27
+ amaMovementTotal: number;
28
+ distanceTotal: number;
29
+ bandFactorPct: number;
30
+ [key: string]: unknown;
31
+ }
32
+ interface WeightedEntry extends SearchEntry {
33
+ weightedScore: number;
34
+ normDistance: number | null;
35
+ normMovement: number | null;
36
+ key: string;
37
+ label: string;
38
+ }
1
39
  declare function parseArgs(argv?: string[]): {
2
40
  dataFile: string | null;
3
41
  er: {
@@ -31,5 +69,16 @@ declare function parseArgs(argv?: string[]): {
31
69
  ama3Weight: number | null;
32
70
  ama4Weight: number | null;
33
71
  };
34
- export { parseArgs };
72
+ declare function updateAmaProfilesFile({ dataFile, meta, winners, sourceResultsFile }: {
73
+ dataFile: string | null;
74
+ meta: DataMeta | null;
75
+ winners: {
76
+ ama1: WeightedEntry;
77
+ ama2: WeightedEntry;
78
+ ama3: WeightedEntry;
79
+ ama4: WeightedEntry;
80
+ };
81
+ sourceResultsFile: string | null;
82
+ }): void;
83
+ export { parseArgs, updateAmaProfilesFile };
35
84
  //# sourceMappingURL=optimizer_high_resolution.d.ts.map
@@ -13,6 +13,7 @@ import { range, geometricRange, percentile } from '../math_utils.js';
13
13
  import { runModuleWorker, splitIntoShards } from '../worker_pool.js';
14
14
  import { getStorage } from '../../modules/storage/index.js';
15
15
  import { normalizeAssetSymbol } from '../../modules/utils/asset_symbols.js';
16
+ import { canonicalPair } from '../../market_adapter/utils/pair_orientation.js';
16
17
  const { readJSON, writeJSON } = getStorage();
17
18
  import { loadLpDataFile, } from '../../market_adapter/lp_chart_runner.js';
18
19
  const AMA_PROFILES_FILE = PATHS.PROFILES.MARKET_PROFILES_JSON;
@@ -290,13 +291,22 @@ function updateAmaProfilesFile({ dataFile, meta, winners, sourceResultsFile }) {
290
291
  const assetBSymbol = normalizeSymbol(meta?.assetB?.symbol);
291
292
  const assetAId = normalizeSymbol(meta?.assetA?.id);
292
293
  const assetBId = normalizeSymbol(meta?.assetB?.id);
293
- const assetA = assetASymbol || assetAId;
294
- const assetB = assetBSymbol || assetBId;
294
+ // Canonical orientation on write, matching the candle cache: a pool fitted
295
+ // from either data orientation produces ONE self-consistent profile entry
296
+ // (`BTS|IOB.XRP|3600`, never also `IOB.XRP|BTS|3600`). The lookup-side
297
+ // tolerance then only has to cover pre-existing/foreign entries.
298
+ const hasIds = Boolean(assetAId && assetBId);
299
+ const order = canonicalPair({ id: hasIds ? assetAId : null, symbol: assetASymbol || assetAId }, { id: hasIds ? assetBId : null, symbol: assetBSymbol || assetBId });
300
+ const assetA = normalizeSymbol(order.assetA.symbol) || normalizeSymbol(order.assetA.id);
301
+ const assetB = normalizeSymbol(order.assetB.symbol) || normalizeSymbol(order.assetB.id);
302
+ const canonAId = normalizeSymbol(order.assetA.id);
303
+ const canonBId = normalizeSymbol(order.assetB.id);
295
304
  if (!assetA || !assetB)
296
305
  return;
297
306
  const intervalSeconds = Number(meta?.intervalSeconds);
298
307
  const intervalLabel = inferIntervalLabel(dataFile, meta);
299
- const key = `${assetA}|${assetB}|${Number.isFinite(intervalSeconds) && intervalSeconds > 0 ? intervalSeconds : intervalLabel}`;
308
+ const intervalKey = Number.isFinite(intervalSeconds) && intervalSeconds > 0 ? intervalSeconds : intervalLabel;
309
+ const key = `${assetA}|${assetB}|${intervalKey}`;
300
310
  const payload = {
301
311
  version: 1,
302
312
  updatedAt: new Date().toISOString(),
@@ -316,8 +326,8 @@ function updateAmaProfilesFile({ dataFile, meta, winners, sourceResultsFile }) {
316
326
  key,
317
327
  assetA,
318
328
  assetB,
319
- assetAId: assetAId || null,
320
- assetBId: assetBId || null,
329
+ assetAId: canonAId || null,
330
+ assetBId: canonBId || null,
321
331
  poolId: meta?.pool || null,
322
332
  intervalSeconds: Number.isFinite(intervalSeconds) && intervalSeconds > 0 ? intervalSeconds : null,
323
333
  intervalLabel,
@@ -351,7 +361,23 @@ function updateAmaProfilesFile({ dataFile, meta, winners, sourceResultsFile }) {
351
361
  },
352
362
  },
353
363
  };
354
- const idx = payload.profiles.findIndex((p) => String(p?.key || '') === key);
364
+ // Replace on canonical key, or on the SAME pair in either orientation so a
365
+ // profile written before canonicalization converges to one entry instead of
366
+ // accumulating a duplicate.
367
+ const sameIntervalAs = (entry) => (Number.isFinite(intervalSeconds) && intervalSeconds > 0 && Number(entry.intervalSeconds) === intervalSeconds)
368
+ || String(entry.intervalLabel || '') === intervalLabel;
369
+ const idx = payload.profiles.findIndex((p) => {
370
+ const entry = p;
371
+ if (!entry)
372
+ return false;
373
+ if (String(entry.key || '') === key)
374
+ return true;
375
+ if (!sameIntervalAs(entry))
376
+ return false;
377
+ const eA = String(entry.assetA || entry.assetAId || '');
378
+ const eB = String(entry.assetB || entry.assetBId || '');
379
+ return (eA === assetA && eB === assetB) || (eA === assetB && eB === assetA);
380
+ });
355
381
  if (idx >= 0)
356
382
  payload.profiles[idx] = profile;
357
383
  else
@@ -744,5 +770,5 @@ else if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).h
744
770
  process.exit(1);
745
771
  });
746
772
  }
747
- export { parseArgs };
773
+ export { parseArgs, updateAmaProfilesFile };
748
774
  //# sourceMappingURL=optimizer_high_resolution.js.map
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Spread-gap width in slots — direct port of calculateGapSlots
3
- * (modules/order/utils/math.ts:1228). The effective target spread is clamped
3
+ * (modules/order/utils/math.ts). The effective target spread is clamped
4
4
  * up to incrementPercent × MIN_SPREAD_FACTOR and the gap never drops below
5
5
  * MIN_SPREAD_ORDERS slots. `incrementPercent`/`targetSpreadPercent` in PERCENT
6
6
  * units, matching the production signature.
@@ -8,7 +8,7 @@
8
8
  declare function computeGapSlots(incrementPercent: number, targetSpreadPercent: number): number;
9
9
  /**
10
10
  * Slope-ratio grid price offset — port of computeGridPriceOffsetPlan
11
- * (market_adapter/core/market_adapter_service.ts:92-119) combined with the
11
+ * (market_adapter/core/market_adapter_service.ts) combined with the
12
12
  * trend/slopeRatio semantics of computeAmaSlopeWeights
13
13
  * (market_adapter/core/strategies/ama_slope_model.ts):
14
14
  *
@@ -17,18 +17,20 @@ declare function computeGapSlots(incrementPercent: number, targetSpreadPercent:
17
17
  * direction = sign(slopePct) (0 inside the neutral zone)
18
18
  * offsetPct = direction × slopeRatio × maxGridPriceOffsetPct
19
19
  *
20
- * Production applies this to startPrice (grid.ts:982: startPrice × (1 +
21
- * offset/100)) only for asymmetricBounds-whitelisted bots; the sim applies it
20
+ * Production applies this to startPrice (modules/order/grid.ts,
21
+ * initializeGrid: startPrice × (1 + offset/100)) only for
22
+ * asymmetricBounds-whitelisted bots; the sim applies it
22
23
  * to the placement center on every grid build when asymmetricBounds is on.
23
24
  */
24
25
  declare function computeGridPriceOffsetPct(slopePct: number, targetSpreadPercent: number): number;
25
26
  /**
26
27
  * Build a persistent grid with FIXED chain prices from a master rail —
27
- * port of createOrderGrid (modules/order/grid.ts:374-505):
28
+ * port of createOrderGrid (modules/order/grid.ts):
28
29
  *
29
30
  * - Master rail: geometric progression starting at √(1±inc) × center and
30
31
  * expanding by (1±inc) steps outward, bounded by
31
- * [center/maxMinRatio, center×maxMinRatio] (grid.ts:428-444).
32
+ * [center/maxMinRatio, center×maxMinRatio] (rail expansion:
33
+ * derivePriceLevels in modules/order/utils/math.ts).
32
34
  * - Spread gap: gapSlots empty slots centered on the center price
33
35
  * (calculateIdealBoundary: boundaryIdx = splitIdx − floor(gap/2) − 1;
34
36
  * sells start at boundaryIdx + gapSlots + 1).
@@ -45,10 +45,6 @@ const DEFAULT_BTS_FEE_CAPITAL = 10000;
45
45
  // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeHuberWindowSlopePct) and the
46
46
  // baseline mirrors botState.gridRangeScalingAmaSlope (re-seeded every reset).
47
47
  const SLOPE_NEUTRAL_ZONE_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
48
- // Spread-gap floor knobs (GRID_LIMITS): the effective target spread is
49
- // clamped up to incrementPercent × MIN_SPREAD_FACTOR and the gap is never
50
- // narrower than MIN_SPREAD_ORDERS slots — mirrored from calculateGapSlots
51
- // (modules/order/utils/math.ts).
52
48
  const RISK_W_DURATION = 1.0; // avg open bars
53
49
  const RISK_W_PEAK_OPEN = 2.0; // peak simultaneous open orders
54
50
  const RISK_W_IMBALANCE = 1.2; // avg |openBuy-openSell|
@@ -171,7 +167,7 @@ function resolveAutoResultsPath(dataPath) {
171
167
  }
172
168
  /**
173
169
  * Spread-gap width in slots — direct port of calculateGapSlots
174
- * (modules/order/utils/math.ts:1228). The effective target spread is clamped
170
+ * (modules/order/utils/math.ts). The effective target spread is clamped
175
171
  * up to incrementPercent × MIN_SPREAD_FACTOR and the gap never drops below
176
172
  * MIN_SPREAD_ORDERS slots. `incrementPercent`/`targetSpreadPercent` in PERCENT
177
173
  * units, matching the production signature.
@@ -185,7 +181,7 @@ function computeGapSlots(incrementPercent, targetSpreadPercent) {
185
181
  }
186
182
  /**
187
183
  * Slope-ratio grid price offset — port of computeGridPriceOffsetPlan
188
- * (market_adapter/core/market_adapter_service.ts:92-119) combined with the
184
+ * (market_adapter/core/market_adapter_service.ts) combined with the
189
185
  * trend/slopeRatio semantics of computeAmaSlopeWeights
190
186
  * (market_adapter/core/strategies/ama_slope_model.ts):
191
187
  *
@@ -194,8 +190,9 @@ function computeGapSlots(incrementPercent, targetSpreadPercent) {
194
190
  * direction = sign(slopePct) (0 inside the neutral zone)
195
191
  * offsetPct = direction × slopeRatio × maxGridPriceOffsetPct
196
192
  *
197
- * Production applies this to startPrice (grid.ts:982: startPrice × (1 +
198
- * offset/100)) only for asymmetricBounds-whitelisted bots; the sim applies it
193
+ * Production applies this to startPrice (modules/order/grid.ts,
194
+ * initializeGrid: startPrice × (1 + offset/100)) only for
195
+ * asymmetricBounds-whitelisted bots; the sim applies it
199
196
  * to the placement center on every grid build when asymmetricBounds is on.
200
197
  */
201
198
  function computeGridPriceOffsetPct(slopePct, targetSpreadPercent) {
@@ -211,11 +208,12 @@ function computeGridPriceOffsetPct(slopePct, targetSpreadPercent) {
211
208
  }
212
209
  /**
213
210
  * Build a persistent grid with FIXED chain prices from a master rail —
214
- * port of createOrderGrid (modules/order/grid.ts:374-505):
211
+ * port of createOrderGrid (modules/order/grid.ts):
215
212
  *
216
213
  * - Master rail: geometric progression starting at √(1±inc) × center and
217
214
  * expanding by (1±inc) steps outward, bounded by
218
- * [center/maxMinRatio, center×maxMinRatio] (grid.ts:428-444).
215
+ * [center/maxMinRatio, center×maxMinRatio] (rail expansion:
216
+ * derivePriceLevels in modules/order/utils/math.ts).
219
217
  * - Spread gap: gapSlots empty slots centered on the center price
220
218
  * (calculateIdealBoundary: boundaryIdx = splitIdx − floor(gap/2) − 1;
221
219
  * sells start at boundaryIdx + gapSlots + 1).
@@ -468,7 +468,8 @@ function resolveAmaConfig(botKey) {
468
468
  const isAmaKeyword = AMA_KEYWORDS.has(rawGridPrice);
469
469
  const botAmaInline = (botMeta.ama && typeof botMeta.ama === 'object') ? botMeta.ama : null;
470
470
  // Priority: inline bot.ama overrides market profile for analysis visibility.
471
- // Production inverts this (profiles first, inline as fallback — market_adapter.ts:694-730).
471
+ // Production inverts this (profiles first, inline as fallback —
472
+ // resolveAmaForBot in market_adapter.ts).
472
473
  if (botAmaInline) {
473
474
  const cfg = {
474
475
  erPeriod: Number(botAmaInline.erPeriod),
@@ -501,13 +502,14 @@ function resolveAmaConfig(botKey) {
501
502
  return cfg;
502
503
  }
503
504
  const marketProfiles = loadMarketProfiles();
504
- // Pair match is case-insensitive: market_profiles.json and bots.json are
505
- // hand-edited, and a case-only difference must not silently drop the
506
- // profile (a strict === here made the AMA/grid config vanish).
505
+ // Pair match is case-insensitive AND orientation-insensitive: a profile may
506
+ // have been fitted from either side of the pair (the candle cache stores
507
+ // canonically). Matching only the bot's typed order would silently drop the
508
+ // profile and fall back to builtin AMA defaults.
507
509
  const selectedProfile = (marketProfiles?.profiles
508
- ? marketProfiles.profiles.find((entry) => isSameAssetSymbol(entry.assetA, botMeta.assetA) &&
509
- isSameAssetSymbol(entry.assetB, botMeta.assetB) &&
510
- Number(entry.intervalSeconds) === 3600)
510
+ ? marketProfiles.profiles.find((entry) => Number(entry.intervalSeconds) === 3600 &&
511
+ ((isSameAssetSymbol(entry.assetA, botMeta.assetA) && isSameAssetSymbol(entry.assetB, botMeta.assetB)) ||
512
+ (isSameAssetSymbol(entry.assetA, botMeta.assetB) && isSameAssetSymbol(entry.assetB, botMeta.assetA))))
511
513
  : null);
512
514
  if (selectedProfile?.amas) {
513
515
  const fallbackKey = selectedProfile.defaultAma || DEFAULT_AMA_KEY;
@@ -33,6 +33,13 @@ declare function embedFunctionSources(fns: Array<Function>): string;
33
33
  * Consumers must define `xMin`, `xMax`, `charts`, `pendingRange`, and `pendingRangeRaf`
34
34
  * before embedding this script block.
35
35
  */
36
- declare const UPLOT_SHARED_SCRIPT = "\nfunction clampXRange(min, max) {\n let nextMin = min, nextMax = max;\n if (!Number.isFinite(nextMin) || !Number.isFinite(nextMax) || nextMax <= nextMin) {\n return { min: xMin, max: xMax };\n }\n if (nextMin < xMin) { nextMax += xMin - nextMin; nextMin = xMin; }\n if (nextMax > xMax) { nextMin -= nextMax - xMax; nextMax = xMax; }\n if (nextMin < xMin) nextMin = xMin;\n if (nextMax > xMax) nextMax = xMax;\n if (nextMax <= nextMin) return { min: xMin, max: xMax };\n return { min: nextMin, max: nextMax };\n}\n\nfunction syncXRange(min, max) {\n pendingRange = clampXRange(min, max);\n if (pendingRangeRaf) return;\n const raf = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame.bind(window) : (fn) => setTimeout(fn, 0);\n pendingRangeRaf = raf(() => {\n const next = pendingRange;\n pendingRange = null;\n pendingRangeRaf = 0;\n if (!next) return;\n charts.forEach(c => c && c.batch(() => c.setScale('x', next)));\n });\n}\n\nfunction bindWheelZoom(chart) {\n chart.root.addEventListener('wheel', (e) => {\n if (e.ctrlKey || e.metaKey || e.altKey) return;\n e.preventDefault();\n e.stopPropagation();\n const rect = chart.root.getBoundingClientRect();\n \n // Correctly calculate plot-relative 'left' for accurate centering\n const left = e.clientX - rect.left - (chart.bbox.left / (chart.pxRatio || 1));\n const center = chart.posToVal(left, 'x');\n \n const s = chart.scales.x || {};\n const currMin = Number.isFinite(s.min) ? s.min : xMin;\n const currMax = Number.isFinite(s.max) ? s.max : xMax;\n const span = currMax - currMin;\n if (!Number.isFinite(span) || span <= 0) return;\n const factor = e.deltaY < 0 ? 0.85 : 1.15;\n const nextSpan = Math.max(1, Math.min(xMax - xMin, span * factor));\n const ratio = (center - currMin) / span;\n syncXRange(center - nextSpan * ratio, center - nextSpan * ratio + nextSpan);\n }, { passive: false });\n}\n\nfunction bindPan(chart) {\n let dragging = false, startClientX = 0, startClientY = 0, startMin = xMin, startMax = xMax, xUnitsPerPx = 0;\n const getScale = () => {\n const s = chart.scales.x || {};\n return { currMin: Number.isFinite(s.min) ? s.min : xMin, currMax: Number.isFinite(s.max) ? s.max : xMax };\n };\n const onMouseMove = (e) => {\n if (!dragging) return;\n \n // Ignore if vertical movement is dominant (likely scrolling)\n if (Math.abs(e.clientY - startClientY) > 20) return;\n \n e.preventDefault();\n const deltaPx = e.clientX - startClientX;\n const deltaVal = deltaPx * xUnitsPerPx;\n syncXRange(startMin - deltaVal, startMax - deltaVal);\n };\n const endDrag = () => {\n if (!dragging) return;\n dragging = false;\n document.body.style.cursor = '';\n window.removeEventListener('mousemove', onMouseMove);\n window.removeEventListener('mouseup', endDrag);\n };\n chart.root.addEventListener('mousedown', (e) => {\n if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;\n const rect = chart.root.getBoundingClientRect();\n if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;\n \n e.preventDefault();\n e.stopPropagation();\n \n dragging = true;\n startClientX = e.clientX;\n startClientY = e.clientY;\n const cur = getScale();\n startMin = cur.currMin; startMax = cur.currMax;\n \n // Calculate units per pixel once at start of drag to avoid sliding bug\n // chart.bbox.width is in device pixels; divide by pxRatio for CSS pixels\n xUnitsPerPx = (cur.currMax - cur.currMin) / (chart.bbox.width / (chart.pxRatio || 1));\n \n document.body.style.cursor = 'grabbing';\n window.addEventListener('mousemove', onMouseMove);\n window.addEventListener('mouseup', endDrag, { once: true });\n });\n\n // Keep the grab cursor while dragging even as the pointer leaves the plot,\n // and end the drag if the window loses focus mid-drag (otherwise the chart\n // keeps panning on the next mousemove after refocus).\n chart.root.addEventListener('mouseleave', () => {\n if (!dragging) return;\n document.body.style.cursor = 'grabbing';\n });\n window.addEventListener('blur', endDrag);\n}\n";
37
- export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, uplotInlineTags };
36
+ declare const UPLOT_SHARED_SCRIPT = "\nfunction clampXRange(min, max) {\n let nextMin = min, nextMax = max;\n if (!Number.isFinite(nextMin) || !Number.isFinite(nextMax) || nextMax <= nextMin) {\n return { min: xMin, max: xMax };\n }\n if (nextMin < xMin) { nextMax += xMin - nextMin; nextMin = xMin; }\n if (nextMax > xMax) { nextMin -= nextMax - xMax; nextMax = xMax; }\n if (nextMin < xMin) nextMin = xMin;\n if (nextMax > xMax) nextMax = xMax;\n if (nextMax <= nextMin) return { min: xMin, max: xMax };\n return { min: nextMin, max: nextMax };\n}\n\n// Safe tick generator for uPlot log axes (scale distr: 3). uPlot 1.6.32's\n// built-in log splits (Je) can loop forever on a narrow price range: its step\n// is reassigned to an intermediate tick that is missing from the nice-number\n// cache, so subsequent rounding collapses the step to 0 and the tick array\n// grows until the engine throws \"Invalid array length\" / runs out of memory\n// (browser tab hang). Emitting only 1/2/5 x 10^d values inside [min, max]\n// never diverges. Assigned per-axis via `splits: logAxisSplits`.\nfunction logAxisSplits(u, axisIdx, min, max) {\n const out = [];\n if (!(min > 0) || !(max > min)) return out;\n const lo = Math.floor(Math.log10(min));\n const hi = Math.ceil(Math.log10(max));\n const mults = [1, 2, 5];\n for (let d = lo; d <= hi; d++) {\n const base = Math.pow(10, d);\n for (let m = 0; m < mults.length; m++) {\n const v = mults[m] * base;\n if (v >= min && v <= max) out.push(v);\n }\n }\n return out.length >= 2 ? out : [min, max];\n}\n\nfunction syncXRange(min, max) {\n pendingRange = clampXRange(min, max);\n if (pendingRangeRaf) return;\n const raf = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame.bind(window) : (fn) => setTimeout(fn, 0);\n pendingRangeRaf = raf(() => {\n const next = pendingRange;\n pendingRange = null;\n pendingRangeRaf = 0;\n if (!next) return;\n charts.forEach(c => c && c.batch(() => c.setScale('x', next)));\n });\n}\n\nfunction bindWheelZoom(chart) {\n chart.root.addEventListener('wheel', (e) => {\n if (e.ctrlKey || e.metaKey || e.altKey) return;\n e.preventDefault();\n e.stopPropagation();\n const rect = chart.root.getBoundingClientRect();\n \n // Correctly calculate plot-relative 'left' for accurate centering\n const left = e.clientX - rect.left - (chart.bbox.left / (chart.pxRatio || 1));\n const center = chart.posToVal(left, 'x');\n \n const s = chart.scales.x || {};\n const currMin = Number.isFinite(s.min) ? s.min : xMin;\n const currMax = Number.isFinite(s.max) ? s.max : xMax;\n const span = currMax - currMin;\n if (!Number.isFinite(span) || span <= 0) return;\n const factor = e.deltaY < 0 ? 0.85 : 1.15;\n const nextSpan = Math.max(1, Math.min(xMax - xMin, span * factor));\n const ratio = (center - currMin) / span;\n syncXRange(center - nextSpan * ratio, center - nextSpan * ratio + nextSpan);\n }, { passive: false });\n}\n\nfunction bindPan(chart) {\n let dragging = false, startClientX = 0, startClientY = 0, startMin = xMin, startMax = xMax, xUnitsPerPx = 0;\n const getScale = () => {\n const s = chart.scales.x || {};\n return { currMin: Number.isFinite(s.min) ? s.min : xMin, currMax: Number.isFinite(s.max) ? s.max : xMax };\n };\n const onMouseMove = (e) => {\n if (!dragging) return;\n \n // Ignore if vertical movement is dominant (likely scrolling)\n if (Math.abs(e.clientY - startClientY) > 20) return;\n \n e.preventDefault();\n const deltaPx = e.clientX - startClientX;\n const deltaVal = deltaPx * xUnitsPerPx;\n syncXRange(startMin - deltaVal, startMax - deltaVal);\n };\n const endDrag = () => {\n if (!dragging) return;\n dragging = false;\n document.body.style.cursor = '';\n window.removeEventListener('mousemove', onMouseMove);\n window.removeEventListener('mouseup', endDrag);\n };\n chart.root.addEventListener('mousedown', (e) => {\n if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;\n const rect = chart.root.getBoundingClientRect();\n if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;\n \n e.preventDefault();\n e.stopPropagation();\n \n dragging = true;\n startClientX = e.clientX;\n startClientY = e.clientY;\n const cur = getScale();\n startMin = cur.currMin; startMax = cur.currMax;\n \n // Calculate units per pixel once at start of drag to avoid sliding bug\n // chart.bbox.width is in device pixels; divide by pxRatio for CSS pixels\n xUnitsPerPx = (cur.currMax - cur.currMin) / (chart.bbox.width / (chart.pxRatio || 1));\n \n document.body.style.cursor = 'grabbing';\n window.addEventListener('mousemove', onMouseMove);\n window.addEventListener('mouseup', endDrag, { once: true });\n });\n\n // Keep the grab cursor while dragging even as the pointer leaves the plot,\n // and end the drag if the window loses focus mid-drag (otherwise the chart\n // keeps panning on the next mousemove after refocus).\n chart.root.addEventListener('mouseleave', () => {\n if (!dragging) return;\n document.body.style.cursor = 'grabbing';\n });\n window.addEventListener('blur', endDrag);\n}\n";
37
+ /**
38
+ * Optional per-bar viewport-clipping helper for draw hooks that walk the whole
39
+ * series every redraw (dynamic-weight fills). Kept out of UPLOT_SHARED_SCRIPT so
40
+ * charts that don't use it don't embed it. Consumers must have x data in
41
+ * u.data[0] and the x-scale min/max on u.scales.x.
42
+ */
43
+ declare const VIEWPORT_CLIP_SCRIPT = "\n// Index window for per-bar draw hooks: binary-search the visible x-range and\n// widen it by one bar on each side so line segments that cross the viewport\n// edge still start/end off-screen. Cuts per-redraw work from O(all bars) to\n// O(visible bars) when a chart is zoomed in.\nfunction visibleBarRange(u, len) {\n const xs = u.data && u.data[0];\n const x = (u.scales && u.scales.x) || {};\n if (!xs || xs.length !== len || !Number.isFinite(x.min) || !Number.isFinite(x.max)) {\n return [0, len - 1];\n }\n const smin = x.min, smax = x.max;\n let a = 0, b = len - 1;\n while (a < b) { const m = (a + b) >> 1; if (xs[m] < smin) a = m + 1; else b = m; }\n const lo = a - 1;\n a = 0; b = len - 1;\n while (a < b) { const m = (a + b + 1) >> 1; if (xs[m] > smax) b = m - 1; else a = m; }\n const hi = a + 1;\n return [Math.max(0, lo), Math.min(len - 1, hi)];\n}\n";
44
+ export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, VIEWPORT_CLIP_SCRIPT, uplotInlineTags };
38
45
  //# sourceMappingURL=chart_utils.d.ts.map
@@ -116,6 +116,29 @@ function clampXRange(min, max) {
116
116
  return { min: nextMin, max: nextMax };
117
117
  }
118
118
 
119
+ // Safe tick generator for uPlot log axes (scale distr: 3). uPlot 1.6.32's
120
+ // built-in log splits (Je) can loop forever on a narrow price range: its step
121
+ // is reassigned to an intermediate tick that is missing from the nice-number
122
+ // cache, so subsequent rounding collapses the step to 0 and the tick array
123
+ // grows until the engine throws "Invalid array length" / runs out of memory
124
+ // (browser tab hang). Emitting only 1/2/5 x 10^d values inside [min, max]
125
+ // never diverges. Assigned per-axis via \`splits: logAxisSplits\`.
126
+ function logAxisSplits(u, axisIdx, min, max) {
127
+ const out = [];
128
+ if (!(min > 0) || !(max > min)) return out;
129
+ const lo = Math.floor(Math.log10(min));
130
+ const hi = Math.ceil(Math.log10(max));
131
+ const mults = [1, 2, 5];
132
+ for (let d = lo; d <= hi; d++) {
133
+ const base = Math.pow(10, d);
134
+ for (let m = 0; m < mults.length; m++) {
135
+ const v = mults[m] * base;
136
+ if (v >= min && v <= max) out.push(v);
137
+ }
138
+ }
139
+ return out.length >= 2 ? out : [min, max];
140
+ }
141
+
119
142
  function syncXRange(min, max) {
120
143
  pendingRange = clampXRange(min, max);
121
144
  if (pendingRangeRaf) return;
@@ -209,5 +232,32 @@ function bindPan(chart) {
209
232
  window.addEventListener('blur', endDrag);
210
233
  }
211
234
  `;
212
- export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, uplotInlineTags };
235
+ /**
236
+ * Optional per-bar viewport-clipping helper for draw hooks that walk the whole
237
+ * series every redraw (dynamic-weight fills). Kept out of UPLOT_SHARED_SCRIPT so
238
+ * charts that don't use it don't embed it. Consumers must have x data in
239
+ * u.data[0] and the x-scale min/max on u.scales.x.
240
+ */
241
+ const VIEWPORT_CLIP_SCRIPT = `
242
+ // Index window for per-bar draw hooks: binary-search the visible x-range and
243
+ // widen it by one bar on each side so line segments that cross the viewport
244
+ // edge still start/end off-screen. Cuts per-redraw work from O(all bars) to
245
+ // O(visible bars) when a chart is zoomed in.
246
+ function visibleBarRange(u, len) {
247
+ const xs = u.data && u.data[0];
248
+ const x = (u.scales && u.scales.x) || {};
249
+ if (!xs || xs.length !== len || !Number.isFinite(x.min) || !Number.isFinite(x.max)) {
250
+ return [0, len - 1];
251
+ }
252
+ const smin = x.min, smax = x.max;
253
+ let a = 0, b = len - 1;
254
+ while (a < b) { const m = (a + b) >> 1; if (xs[m] < smin) a = m + 1; else b = m; }
255
+ const lo = a - 1;
256
+ a = 0; b = len - 1;
257
+ while (a < b) { const m = (a + b + 1) >> 1; if (xs[m] > smax) b = m - 1; else a = m; }
258
+ const hi = a + 1;
259
+ return [Math.max(0, lo), Math.min(len - 1, hi)];
260
+ }
261
+ `;
262
+ export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, VIEWPORT_CLIP_SCRIPT, uplotInlineTags };
213
263
  //# sourceMappingURL=chart_utils.js.map
@@ -26,6 +26,7 @@ interface AmaDefaultsInput {
26
26
  declare function loadMarketProfiles(filePath?: string | null | undefined): {
27
27
  profiles?: Array<Record<string, unknown>>;
28
28
  } | null;
29
+ declare function findMarketProfile(profiles: unknown, meta?: MarketMeta): Record<string, unknown> | null;
29
30
  declare const TRADINGVIEW_PREFS_KEY_PREFIX = "dexbot2-tradingview-uplot-v3";
30
31
  declare const TRADINGVIEW_SYNC_KEY = "dexbot2-tradingview-sync";
31
32
  declare function sanitizeStorageComponent(value: unknown, fallback: string): string;
@@ -70,5 +71,5 @@ interface TvChartInput extends AmaDefaultsInput {
70
71
  [key: string]: unknown;
71
72
  }
72
73
  declare function generateHTML(data: TvChartInput, title?: string): string;
73
- export { generateHTML, normalizeCandle, loadMarketProfiles, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
74
+ export { generateHTML, normalizeCandle, loadMarketProfiles, findMarketProfile, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
74
75
  //# sourceMappingURL=tradingview_uplot_chart_generator.d.ts.map
@@ -65,8 +65,14 @@ function findMarketProfile(profiles, meta = {}) {
65
65
  return false;
66
66
  const e = entry;
67
67
  if (assetA && assetB) {
68
- const matchesPair = (String(e.assetA) === String(assetA) || String(e.assetAId) === String(assetA))
69
- && (String(e.assetB) === String(assetB) || String(e.assetBId) === String(assetB));
68
+ // Orientation-insensitive like the other market-profile consumers:
69
+ // a profile may have been fitted from either side of the pair.
70
+ const eA = [String(e.assetA), String(e.assetAId)];
71
+ const eB = [String(e.assetB), String(e.assetBId)];
72
+ const targetA = String(assetA);
73
+ const targetB = String(assetB);
74
+ const matchesPair = (eA.includes(targetA) && eB.includes(targetB))
75
+ || (eA.includes(targetB) && eB.includes(targetA));
70
76
  if (!matchesPair)
71
77
  return false;
72
78
  }
@@ -571,6 +577,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
571
577
  <div id="toolbar">
572
578
  <div class="toolbar-row primary-toolbar-row">
573
579
  <div class="group">
580
+ <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>
574
581
  <div class="indicator">
575
582
  <span class="tag">pair</span>
576
583
  <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)}">
@@ -604,7 +611,6 @@ function generateHTML(data, title = 'TradingView Style Research') {
604
611
  <button type="button" class="step-btn" id="vwap-bars-dec">▼</button>
605
612
  </span>
606
613
  </div>
607
- <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>
608
614
  ${(((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>' : '')}
609
615
  </div>
610
616
  </div>
@@ -2227,7 +2233,15 @@ function generateHTML(data, title = 'TradingView Style Research') {
2227
2233
  segTop = [];
2228
2234
  segBot = [];
2229
2235
  };
2230
- for (let i = 0; i < xs.length; i++) {
2236
+ // Clip to the visible bar window (same rule as the grid-reset
2237
+ // band below) so a zoomed-in redraw does not walk every bar.
2238
+ // One bar of padding each side keeps segments that cross the
2239
+ // viewport edge connected; only contiguous valid runs are
2240
+ // painted, so off-screen bars add no pixels either way.
2241
+ const idxs = (u.series[0] && u.series[0].idxs) ? u.series[0].idxs : [0, xs.length - 1];
2242
+ const iLo = Math.max(0, idxs[0] - 1);
2243
+ const iHi = Math.min(xs.length - 1, idxs[1] + 1);
2244
+ for (let i = iLo; i <= iHi; i++) {
2231
2245
  const a = currentAma[i];
2232
2246
  const up = currentRangeUpper[i];
2233
2247
  const lo = currentRangeLower[i];
@@ -3878,5 +3892,5 @@ function generateHTML(data, title = 'TradingView Style Research') {
3878
3892
  </body>
3879
3893
  </html>`;
3880
3894
  }
3881
- export { generateHTML, normalizeCandle, loadMarketProfiles, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
3895
+ export { generateHTML, normalizeCandle, loadMarketProfiles, findMarketProfile, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
3882
3896
  //# sourceMappingURL=tradingview_uplot_chart_generator.js.map