dexbot 1.6.15 → 1.6.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +4 -4
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
- package/claw/modules/chain_queries.ts +3 -3
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
- package/dist/analysis/bot_key_utils.js +9 -7
- package/dist/analysis/chart_utils.d.ts +9 -2
- package/dist/analysis/chart_utils.js +51 -1
- package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +23 -9
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
- package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
- package/dist/dexbot.js +89 -138
- package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
- package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
- package/dist/market_adapter/inputs/window_cache.js +53 -17
- package/dist/market_adapter/lp_chart_core.js +1 -0
- package/dist/market_adapter/utils/chain.js +4 -3
- package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
- package/dist/market_adapter/utils/pair_orientation.js +142 -0
- package/dist/modules/account_bots.d.ts +40 -3
- package/dist/modules/account_bots.js +77 -37
- package/dist/modules/account_orders.d.ts +4 -1
- package/dist/modules/account_orders.js +4 -1
- package/dist/modules/bitshares-native/resolvers.js +3 -3
- package/dist/modules/bitshares_client.d.ts +12 -10
- package/dist/modules/bitshares_client.js +12 -10
- package/dist/modules/bot_settings.js +3 -3
- package/dist/modules/chain_keys.d.ts +6 -2
- package/dist/modules/chain_keys.js +5 -1
- package/dist/modules/chain_orders.d.ts +6 -2
- package/dist/modules/chain_orders.js +6 -2
- package/dist/modules/constants.d.ts +11 -0
- package/dist/modules/constants.js +41 -7
- package/dist/modules/credit_pricing.d.ts +20 -1
- package/dist/modules/credit_pricing.js +23 -1
- package/dist/modules/credit_runtime.js +33 -16
- package/dist/modules/dexbot_class.d.ts +6 -2
- package/dist/modules/dexbot_class.js +8 -3
- package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
- package/dist/modules/dexbot_cow_runtime.js +47 -66
- package/dist/modules/dexbot_maintenance_runtime.js +68 -10
- package/dist/modules/graceful_shutdown.d.ts +6 -2
- package/dist/modules/graceful_shutdown.js +6 -2
- package/dist/modules/launcher/bot_supervisor.js +4 -0
- package/dist/modules/launcher/credential_daemon.d.ts +14 -2
- package/dist/modules/launcher/credential_daemon.js +60 -26
- package/dist/modules/launcher/launch_modes.js +6 -3
- package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
- package/dist/modules/launcher/monolithic_runtime.js +60 -1
- package/dist/modules/launcher/runtime_mode.d.ts +79 -0
- package/dist/modules/launcher/runtime_mode.js +223 -0
- package/dist/modules/market_adapter_whitelist.d.ts +8 -0
- package/dist/modules/market_adapter_whitelist.js +8 -0
- package/dist/modules/order/accounting.d.ts +15 -1
- package/dist/modules/order/accounting.js +15 -1
- package/dist/modules/order/async_lock.d.ts +9 -3
- package/dist/modules/order/async_lock.js +9 -3
- package/dist/modules/order/export.d.ts +0 -5
- package/dist/modules/order/export.js +0 -5
- package/dist/modules/order/format.d.ts +6 -4
- package/dist/modules/order/format.js +6 -4
- package/dist/modules/order/grid.d.ts +36 -18
- package/dist/modules/order/grid.js +186 -33
- package/dist/modules/order/index.d.ts +16 -1
- package/dist/modules/order/index.js +1 -1
- package/dist/modules/order/logger_state.d.ts +1 -1
- package/dist/modules/order/logger_state.js +1 -1
- package/dist/modules/order/manager.d.ts +30 -7
- package/dist/modules/order/manager.js +108 -12
- package/dist/modules/order/strategy.d.ts +5 -0
- package/dist/modules/order/strategy.js +23 -2
- package/dist/modules/order/sync_engine.d.ts +26 -11
- package/dist/modules/order/sync_engine.js +26 -11
- package/dist/modules/order/utils/math.d.ts +100 -22
- package/dist/modules/order/utils/math.js +106 -22
- package/dist/modules/order/utils/order.d.ts +77 -20
- package/dist/modules/order/utils/order.js +125 -27
- package/dist/modules/order/utils/system.d.ts +107 -11
- package/dist/modules/order/utils/system.js +176 -11
- package/dist/modules/order/utils/validate.d.ts +8 -3
- package/dist/modules/order/utils/validate.js +10 -3
- package/dist/modules/types.d.ts +35 -2
- package/dist/modules/utils/asset_symbols.d.ts +5 -5
- package/dist/modules/utils/asset_symbols.js +5 -5
- package/dist/modules/utils/errors.d.ts +2 -1
- package/dist/modules/utils/errors.js +2 -1
- package/dist/scripts/analyze-credit.js +64 -23
- package/dist/scripts/bts_distribution.d.ts +66 -0
- package/dist/scripts/bts_distribution.js +2102 -0
- package/dist/scripts/rich_list.d.ts +32 -0
- package/dist/scripts/rich_list.js +16 -8
- package/dist/scripts/token_distribution.d.ts +45 -0
- package/dist/scripts/token_distribution.js +1870 -0
- package/dist/unlock.js +91 -42
- package/docs/BITSHARES_ONBOARDING.md +7 -0
- package/docs/COW_INVARIANTS.md +7 -1
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -3
- package/docs/GRID_PRICE_INVARIANT.md +6 -0
- package/docs/GRID_RECALCULATION.md +18 -6
- package/docs/LIFECYCLE.md +8 -8
- package/docs/LOGGING.md +9 -0
- package/docs/MPA_CREDIT_USAGE.md +3 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +121 -4
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +5 -5
- package/docs/architecture.md +98 -1
- package/market_adapter/README.md +10 -3
- package/package.json +5 -1
- package/scripts/README.md +85 -148
- package/tests/README.md +29 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,58 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.6.17] - 2026-10-30 - Last-Fill Direction Guard, Spread-Correction Stall Naming & Chain-Truth Funding, Owed-Crawl Consumption, Restart Auth-Before-Stop, Pool-Priced LP Collateral, Supply Distribution Analyzers
|
|
6
|
+
|
|
7
|
+
### 2026-10-30
|
|
8
|
+
|
|
9
|
+
- **Feat(scripts)**: add a BTS supply distribution analyzer — `scripts/bts_distribution.ts` (`npm run distribution`) is a read-only live-chain report that buckets the core asset into call-order collateral, global and individual settlement funds (with individual debt and force-settlement parameters), governance tickets, vesting and legacy balances, liquidity pools, SameT/credit funds, HTLC escrow and asset fee pools, then reports the leftover as a derived liquid residual compared against total supply and a derived circulating float (optional external reference). It also pulls the liquid rich list from `asset_api::get_asset_holders` (retrying on a node without that API), tags exchange-like account names as a heuristic, and can page the full holder list to split the residual into account balances, blinded balances and order books with concentration and balance bands. Output is a colorized terminal report plus a self-contained HTML donut report under the gitignored `analysis/charts/`. Documented in `scripts/README.md`; verified with a clean build, `check:any`, and live runs in default and full-rich-list modes.
|
|
10
|
+
|
|
11
|
+
- **Feat(scripts)**: add a per-token companion analyzer — `scripts/token_distribution.ts` (`npm run token-distribution`) buckets a single asset into free balances, limit orders, liquidity pools, vesting balances, P2P credit offers and deal collateral, SameT funds, HTLC escrow, accumulated market fees and blinded supply, reconciling every bucket against `current_supply`. Liquidity is grouped by counterpart asset and reported as a separate donut, and a 3% price-change table combines orderbook and constant-product pool depth per market (token sellable at −3%, buyable at +3%, each as a share of total supply), with pool depth net of the taker fee and capped orderbook rows marked. Read-only, with `--json` and `--no-orders` modes; documented in `scripts/README.md`.
|
|
12
|
+
|
|
13
|
+
- **Tune(ama)**: make the slowPeriod ladder exact −9% response steps — AMA2–AMA4 are now derived from AMA1 (62.1) so each preset lowers the effective smoothing coefficient by ~9% at the typical ER (`AMA_CONVERGENCE_ER_AVG` 0.151), where the old fixed +16% period ladder shrank the response difference toward the slow end (−9.4/−8.7/−7.8%). AMA2 72.0 → 71.5, AMA3 83.6 → 83.5, AMA4 96.9 → 99.3 (unrounded 62.10/71.48/83.46/99.27); AMA4 is the only material change (~4.7% lower ER→0 noise floor, ~1.25% less responsive at ER 0.151, ~16 extra warmup bars), AMA1–AMA3 are effectively unchanged. Docs, chart preset annotations and the Huber backtest default (now derived from `MARKET_ADAPTER.AMAS` instead of hardcoded) are aligned. Covered by `test_bot_defaults_parity`, `test_market_adapter_logic` and `test_lp_chart`.
|
|
14
|
+
|
|
15
|
+
- **Tune(ama)**: raise the AMA slope ceiling default from 0.09 to 0.1 — `DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT` now needs a stronger per-bar trend before reaching full influence, de-sensitizing range asymmetry, grid price offset and buy/sell weight tilt to the same slope magnitude; the AMA-slope grid-reset trigger threshold scales with the ceiling, so it rises proportionally. TradingView/grid-reset simulator fallbacks and the research-doc default follow the canonical constant; per-bot `amaSlope.maxSlopePct` overrides still win. Behavioral default change for bots without an explicit override. Covered by `test_grid_reset_sim`, `test_ama_slope_model` and `test_market_adapter_logic`.
|
|
16
|
+
|
|
17
|
+
- **Fix(guard)**: last-fill guard blocks only higher buys and lower sells — the guard judged placements against a price band around the last fill and never read the fill's side, so it blocked profitable placements within half an increment of the fill (exactly where spread correction places) and blocked buy-backs *below* a SELL fill. It is replaced by the direction rule `BUY blocked at/above the pivot`, `SELL blocked at/below the pivot` in `modules/order/utils/system.ts` (equal price stays blocked to prevent the immediate re-fill loop; a cold pivot or unrecorded fill side still disables the guard). The increment no longer participates but stays in the signature so call sites and logs are unchanged, and `LastFillGuardResult` drops `halfInc`. Live impact: a sweep no longer freezes spread repair for the rest of the band. Covered by a rewritten `tests/test_last_fill_guard.ts` plus re-solved invariants in `tests/test_grid_price_invariant_wiring.ts`.
|
|
18
|
+
|
|
19
|
+
- **Fix(spread)**: plan only placeable tightening slots and name the stalls — the correction planned candidates the broadcast guard was guaranteed to drop, because its crossing floor preferred a fresh live read over the fill anchor and had no planner-side last-fill filter. `passesLastFill` (exported next to `resolveLastFillGuardReference` and reused by the COW runtime, so planner and guard cannot resolve different pivots) is now applied to every candidate pool and boundary promotion before the quota slice; an empty side is reported as the `last-fill-blocked` stall and survives the starvation-fallback merge instead of collapsing to no-candidates; a rail reservation above the chain free balance is named and flagged `OVERSUBSCRIBED`; and the out-of-spread clock is cleared only after sustained tolerance or a placement, with the fund and geometry escalations on their own windows. The crawl-ledger drop log now carries side split, net, age and boundary delta. Files: `order/utils/system.ts`, `order/grid.ts`, `dexbot_cow_runtime.ts`, `dexbot_maintenance_runtime.ts`, `order/manager.ts`, `constants.ts`, `types.ts`, `dexbot_class.ts`; covered by new `tests/test_spread_last_fill_planning.ts` and updated `test_spread_market_reference`, `test_stale_grid_hardening`, `test_dexbot_maintenance_runtime_dynamic_weights`, `test_targeted_drift_reconcile`.
|
|
20
|
+
|
|
21
|
+
- **Fix(spread)**: fund from chain truth and re-anchor the boundary from the fill — two self-referential calculations could only be broken from outside. (1) The budget vetoed its own placement: `available = chainFree − virtual` then spends it on that same projection, so a rail sized from a larger balance (or from resting inventory) can leave `available` at 0 forever; `deriveChainTruthFundBudget` (`order/utils/math.ts`) re-derives the budget for a known candidate set as `min(chainFree, min(virtual, Σ candidate ideals))`, bounded on both sides and still rejected at broadcast if over-committed, while a zero caused by fees or an empty balance is honoured unchanged. (2) A boundary crawl is ±1 slot per committed fill, so once a sweep leaves the window behind the fill no tightening slot can be placed and the stranded orders cannot rotate down either; `reanchorBoundaryFromLastFill` (`order/utils/system.ts`, applied from `calculateTargetGrid`) anchors the fill (`SELL` fill at slot f → boundary ≥ f − gapSlots; `BUY` fill at slot f → boundary ≤ f − 1), fail-closed on fill provenance, on-ladder price and `validatePersistedBoundary`. A per-fill pair ledger was rejected on purpose: sizes must follow the side budget, and a SELL fill returns quote while the same-side repair needs base. Covered by `tests/test_chain_truth_funding.ts` and `tests/test_boundary_fill_reanchor.ts`; documented in the architecture, COW invariant and fund-movement docs plus retrospective §9.9.
|
|
22
|
+
|
|
23
|
+
- **Fix(crawls)**: consume only the owed fill crawls a derivation applied — the pending-crawl ledger records one relative boundary delta per shift-eligible fill because the batch that sees a fill may not commit a boundary, but the derivation folds only a subset (own-batch slots are deduped, edge slots never crawl, the cross-chunk cap bounds one plan) while the commit cleared *all* of it, so an owed record the derivation could not apply vanished. Live signature: seven fills swept slots and two commits each dropped owed crawls, leaving the boundary seven levels behind and the sell window below the last sale. `deriveTargetBoundary` now returns `consumedCrawlIds` (applied records plus the ones deliberately never counted; a capped fold consumes a same-side prefix so the remainder stays owed exactly once), the plan carries it through `buildSuccessResult` → `CowResult` → both `_commitWorkingGrid` call sites, and `_consumePendingFillCrawls` drops exactly those records (matched by `slotId` + `ts`) while logging `Dropped N … kept=M`. A commit without the wire consumes nothing; `_clearPendingFillCrawls` keeps its explicit allowed-loss meaning. The recorder still dedupes per slot and caps the ledger at 500, so no age cap is needed. Covered by new `tests/test_crawl_ledger_consumption.ts` plus updated pending-fill and market-scenario tests.
|
|
24
|
+
|
|
25
|
+
- **Fix(restart)**: verify the master password before stopping the credential daemon — a failed `dexbot restart` used to stop the live daemon first and then abort on a wrong or cancelled password, leaving every bot without key access until a later successful start. Both restart-all paths (monolithic and isolated supervisor) now authenticate first and only stop the existing daemon once the secret is verified, handing the verified secret to `ensureCredentialDaemon` so it does not prompt twice; a failed authentication exits non-zero without touching the daemon or signalling the runtime. Files: `unlock.ts`, `modules/launcher/credential_daemon.ts` (`authenticateCredential`, optional pre-verified `vaultSecret`); covered by `tests/test_restart_password_gate.ts`.
|
|
26
|
+
|
|
27
|
+
- **Refactor(restart)**: type the vault secret and clear it after daemon handoff — the pre-verified secret was typed `unknown` and the launcher-side reference stayed live until the restart block ended. `VaultSecret` is now exported from `chain_keys` and used by the restart/daemon-start APIs, and `clearVaultSecret` is called in a `finally` covering every startup path (successful bootstrap handoff, spawn/startup failure, bootstrap server creation failure, bootstrap path-file write failure), with both restart paths clearing the caller's reference even if daemon startup throws. A caller-supplied `vaultSecret` is documented as consumed and must not be reused. Nothing is persisted: the secret stays in process memory, is never logged or written to disk, and hex strings cannot be zeroed in place in V8, so the helper nulls the fields and lets GC reclaim them. Covered by `test_restart_password_gate` and `test_credential_daemon_controller_output`.
|
|
28
|
+
|
|
29
|
+
- **Fix(credit)**: value LP-share collateral at the pool market price — `dexbot credit` and the runtime's conversion-rate resolver used the offer's fixed `acceptable_collateral` price for liquidity-pool share collateral, which is a contract haircut and can go stale, so the reported CR was false for LP shares (e.g. 1.111 instead of the pool-based 1.399). New `selectCollateralConversionRate()` (`modules/credit_pricing.ts`) prefers the live pool value for LP shares and otherwise keeps the offer price first with the pool rate as fallback; `scripts/analyze-credit.ts` uses it and tags `Avar. CR` rows with `pool`/`offer` while keeping the active deal's offer for `Curr. CR`, and `_resolveCreditConversionRate()` (`modules/credit_runtime.ts`) is pool-first for LP shares so collateral distribution matches the borrow gate. LP-share CR uses pure pool reserves/supply with no fee or slippage deduction; non-LP collateral is unchanged, and multi-item groups sharing an LP collateral now split at market-value CR. Covered by `test_credit_pricing`, `test_analyze_credit`, `test_credit_conversion_fallback` and `test_credit_runtime`.
|
|
30
|
+
|
|
31
|
+
## [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
|
|
32
|
+
|
|
33
|
+
### 2026-10-18
|
|
34
|
+
|
|
35
|
+
- **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`.
|
|
36
|
+
|
|
37
|
+
- **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.
|
|
38
|
+
|
|
39
|
+
- **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.
|
|
40
|
+
|
|
41
|
+
- **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`.
|
|
42
|
+
|
|
43
|
+
- **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`.
|
|
44
|
+
|
|
45
|
+
- **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`.
|
|
46
|
+
|
|
47
|
+
- **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.
|
|
48
|
+
|
|
49
|
+
- **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.
|
|
50
|
+
|
|
51
|
+
- **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`).
|
|
52
|
+
|
|
53
|
+
- **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`.
|
|
54
|
+
|
|
55
|
+
- **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.
|
|
56
|
+
|
|
5
57
|
## [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
58
|
|
|
7
59
|
### 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
|
|
323
|
-
dexbot restart
|
|
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).
|
|
@@ -111,7 +111,7 @@ node dist/analysis/tradingview/analyze_tradingview.js \
|
|
|
111
111
|
1. Reads `profiles/bots.json` to find the bot's `assetA`, `assetB`, and `ama` settings.
|
|
112
112
|
2. Resolves the candle file at `market_adapter/data/market_adapter_<bot-key>_1h.json`.
|
|
113
113
|
3. Looks up the matching market profile in `profiles/market_profiles.json` for AMA defaults.
|
|
114
|
-
4. AMA settings priority: bot-specific `ama` object > market profile > constants (AMA3, slowPeriod 83.
|
|
114
|
+
4. AMA settings priority: bot-specific `ama` object > market profile > constants (AMA3, slowPeriod 83.5).
|
|
115
115
|
|
|
116
116
|
> The candle file must exist — run the market adapter LP exporter first if needed (see [Getting Blockchain Data](#getting-blockchain-data)).
|
|
117
117
|
|
|
@@ -189,7 +189,7 @@ Indicator on/off state is not a generation-time flag: `SMA`, `VWMA`, `AMA`, `Ran
|
|
|
189
189
|
| `--sma-period <n>` | SMA period | `500` |
|
|
190
190
|
| `--ama-er-period <n>` | AMA ER period | `781` |
|
|
191
191
|
| `--ama-fast-period <n>` | AMA fast period | `5.2` |
|
|
192
|
-
| `--ama-slow-period <n>` | AMA slow period | `83.
|
|
192
|
+
| `--ama-slow-period <n>` | AMA slow period | `83.5` |
|
|
193
193
|
| `--vwap-bars <n>` | Rolling VWMA window | `500` |
|
|
194
194
|
| `--no-sma` | Disable SMA | — |
|
|
195
195
|
| `--no-vwap` | Disable VWMA | — |
|
|
@@ -166,7 +166,7 @@ All panels share aligned vertical time grid lines, and the bottom output panel s
|
|
|
166
166
|
|------|-------|---------|---------|
|
|
167
167
|
| **nz%** | 0–1 | 0.00 | Neutral zone: dead-band below which offset is forced to 0 |
|
|
168
168
|
| **lb** | 4–32 | 16 | Logarithmic. Lookback bars for AMA slope calculation |
|
|
169
|
-
| **amaS%** | 0.06–0.12 | 0.
|
|
169
|
+
| **amaS%** | 0.06–0.12 | 0.1 | Logarithmic. Gear ratio for per-bar AMA slope saturation |
|
|
170
170
|
| **kalS%** | 0.75–1.5 | 1.2 | Logarithmic. Gear ratio for Kalman composite saturation |
|
|
171
171
|
| **clip%** | 0–20 | 10 | Percentile clip: filters extreme inputs (0 = off) |
|
|
172
172
|
|
|
@@ -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;
|
|
45
|
-
//
|
|
46
|
-
//
|
|
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
|
@@ -177,11 +177,13 @@ function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel) {
|
|
|
177
177
|
const move = results.map((r) => r.movement);
|
|
178
178
|
const cacheSlow = metricCache.map((m) => m.slow);
|
|
179
179
|
const cacheMove = metricCache.map((m) => m.movement);
|
|
180
|
+
// Current built-in presets: AMA1 is the λ=0.0031 fit, AMA2–AMA4 follow the
|
|
181
|
+
// exact −9%/step effective-smoothing ladder (see MARKET_ADAPTER.AMAS).
|
|
180
182
|
const amaAnnotations = [
|
|
181
183
|
{ label: 'AMA1', lambda: 0.0031, slow: 62.1, color: '#ef5350' },
|
|
182
|
-
{ label: 'AMA2', lambda: 0.0025, slow:
|
|
183
|
-
{ label: 'AMA3', lambda: 0.00185, slow: 83.
|
|
184
|
-
{ label: 'AMA4', lambda: 0.0013, slow:
|
|
184
|
+
{ label: 'AMA2', lambda: 0.0025, slow: 71.5, color: '#fb8c00' },
|
|
185
|
+
{ label: 'AMA3', lambda: 0.00185, slow: 83.5, color: '#5c9ee6' },
|
|
186
|
+
{ label: 'AMA4', lambda: 0.0013, slow: 99.3, color: '#26a69a' },
|
|
185
187
|
].filter(a => a.lambda >= xs[0] && a.lambda <= xs[xs.length - 1]);
|
|
186
188
|
return `<!DOCTYPE html>
|
|
187
189
|
<html lang="en">
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
294
|
-
|
|
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
|
|
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:
|
|
320
|
-
assetBId:
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
21
|
-
* offset/100)) only for
|
|
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
|
|
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] (
|
|
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
|
|
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
|
|
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
|
|
198
|
-
* offset/100)) only for
|
|
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
|
|
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] (
|
|
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 —
|
|
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:
|
|
505
|
-
//
|
|
506
|
-
//
|
|
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) =>
|
|
509
|
-
isSameAssetSymbol(entry.assetB, botMeta.assetB)
|
|
510
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|