dexbot 1.6.13 → 1.6.15
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 +66 -4
- package/README.md +2 -2
- package/analysis/README.md +6 -6
- package/analysis/tradingview/README.md +2 -1
- package/claw/README.md +7 -7
- package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
- package/claw/modules/claw_catalog.ts +8 -4
- package/claw/modules/dexbot_profiles.ts +59 -15
- package/claw/modules/types.ts +2 -1
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/claw/skills/margin-trading/SKILL.md +1 -1
- package/claw/skills/margin-trading/references/position-management.md +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
- package/dist/dexbot.js +23 -3
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
- package/dist/modules/account_bots.d.ts +10 -6
- package/dist/modules/account_bots.js +13 -10
- package/dist/modules/account_orders.d.ts +36 -4
- package/dist/modules/account_orders.js +76 -5
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
- package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
- package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
- package/dist/modules/bitshares-native/subscriptions.js +1 -1
- package/dist/modules/bot_defaults.d.ts +29 -4
- package/dist/modules/bot_defaults.js +65 -10
- package/dist/modules/bot_settings.d.ts +4 -0
- package/dist/modules/bot_settings.js +58 -21
- package/dist/modules/config.js +6 -1
- package/dist/modules/constants.d.ts +13 -5
- package/dist/modules/constants.js +36 -5
- package/dist/modules/credit_runtime.d.ts +35 -5
- package/dist/modules/credit_runtime.js +219 -38
- package/dist/modules/dexbot_class.d.ts +23 -0
- package/dist/modules/dexbot_class.js +60 -17
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
- package/dist/modules/dexbot_cow_runtime.js +350 -64
- package/dist/modules/dexbot_credential_client.d.ts +1 -16
- package/dist/modules/dexbot_credential_client.js +1 -1
- package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
- package/dist/modules/dexbot_fill_runtime.js +16 -8
- package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
- package/dist/modules/dexbot_maintenance_runtime.js +104 -70
- package/dist/modules/dexbot_startup_runtime.js +15 -2
- package/dist/modules/dexbot_state_recovery.js +17 -1
- package/dist/modules/key_store.d.ts +0 -5
- package/dist/modules/key_store.js +1 -1
- package/dist/modules/order/accounting.js +11 -11
- package/dist/modules/order/export.js +4 -4
- package/dist/modules/order/format.d.ts +15 -1
- package/dist/modules/order/format.js +19 -1
- package/dist/modules/order/genesis_policy.d.ts +1 -1
- package/dist/modules/order/genesis_policy.js +1 -1
- package/dist/modules/order/grid.d.ts +141 -12
- package/dist/modules/order/grid.js +666 -92
- package/dist/modules/order/grid_reconcile.d.ts +1 -1
- package/dist/modules/order/grid_reconcile.js +9 -8
- package/dist/modules/order/grid_reconcile_internal.js +61 -58
- package/dist/modules/order/index.d.ts +37 -9
- package/dist/modules/order/logger.js +2 -2
- package/dist/modules/order/manager.d.ts +10 -2
- package/dist/modules/order/manager.js +56 -31
- package/dist/modules/order/strategy.d.ts +2 -2
- package/dist/modules/order/strategy.js +51 -21
- package/dist/modules/order/sync_engine.js +22 -9
- package/dist/modules/order/utils/math.d.ts +101 -29
- package/dist/modules/order/utils/math.js +215 -84
- package/dist/modules/order/utils/order.d.ts +58 -58
- package/dist/modules/order/utils/order.js +135 -106
- package/dist/modules/order/utils/system.d.ts +193 -6
- package/dist/modules/order/utils/system.js +394 -31
- package/dist/modules/order/utils/validate.d.ts +1 -1
- package/dist/modules/order/utils/validate.js +71 -59
- package/dist/modules/runtime_settings.d.ts +1 -1
- package/dist/modules/runtime_settings.js +3 -3
- package/dist/modules/types.d.ts +55 -4
- package/dist/scripts/analyze-credit.js +44 -27
- package/dist/scripts/analyze-orders.d.ts +1 -1
- package/dist/scripts/analyze-orders.js +4 -4
- package/dist/scripts/diagnose-pool-history.js +35 -30
- package/dist/scripts/divergence-calc.js +6 -6
- package/dist/scripts/pnl.js +1 -1
- package/dist/scripts/rich_list.d.ts +18 -0
- package/dist/scripts/rich_list.js +461 -0
- package/dist/scripts/run-tests.js +80 -4
- package/dist/scripts/validate_bots.d.ts +1 -1
- package/dist/scripts/validate_bots.js +3 -3
- package/dist/unlock.d.ts +2 -1
- package/dist/unlock.js +11 -5
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
- package/docs/COW_INVARIANTS.md +12 -6
- package/docs/DEXBOT_COMPARISON.md +7 -7
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
- package/docs/GRID_PRICE_INVARIANT.md +3 -3
- package/docs/GRID_RECALCULATION.md +4 -1
- package/docs/GRID_RECONCILE.md +4 -4
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +30 -1
- package/docs/MPA_CREDIT_USAGE.md +11 -6
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
- package/docs/README.md +3 -3
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +62 -8
- package/docs/developer_guide.md +12 -3
- package/market_adapter/README.md +4 -4
- package/modules/README.md +1 -1
- package/package.json +2 -1
- package/scripts/README.md +59 -32
- package/tests/README.md +12 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,68 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [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
|
+
|
|
7
|
+
### 2026-10-16
|
|
8
|
+
|
|
9
|
+
- **Fix(order)**: keep grid level identity price-based, not amount-based — a bot on a low-precision quote asset (precision 4) placed only one of 20 sells and collapsed its outside→center pairing, because `priceSlotEqual(price, price, assetPrecision)` rounded a PRICE through an asset AMOUNT precision: 0.000318 and 0.000343 both round to 3, so every adjacent level looked like the same level and every CREATE after the first was rejected as a collision. The overloaded helper is replaced by three explicit identities: `pricesOnSameLevel` (chain-representable tolerance, min across both types, now clamped to half a grid step so a dust-inflated tolerance cannot merge adjacent levels) for any chain-derived price, exact `sameGridPrice` for grid-vs-grid, and genesis-aware `sameGridLevel` (falls back to `sameGridPrice` out of rail). Every production call site is repointed, `isChainPriceOutOfGrid` excuses only genuine float dust at the rail edge (capped chain tolerance) instead of a whole below-rail dip-protection band, and the test-only `findPriceCollision` is deleted. Covered by `tests/test_price_collision_guard.ts`, `tests/test_sync_out_of_grid_defer.ts` and `tests/test_validate_create_target_slots.ts`.
|
|
10
|
+
|
|
11
|
+
- **Fix(order)**: harden spread correction against concurrent plan invalidation — a plan invalidated between planning and commit (a concurrent fill rebalance advanced the master version or took the destination slot) was refused fail-closed, and an out-of-spread grid cannot self-heal because it produces no fill to re-plan, so the bot stayed stale. `checkSpreadCondition` now holds the refcounted broadcast region across the whole plan/broadcast/retry loop (released in `finally`); `getOccupiedCorrectionSlots`/`resolveOccupiedCorrection` re-derive or withhold a plan whose CREATE destination was taken; a transient refusal triggers a bounded `replanSpreadCorrectionFromFreshMaster` (`TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS`, default 2); `trackOutOfSpreadStaleness` tolerates transient refusals up to `TIMING.SPREAD_STALE_TRANSIENT_GRACE` before escalating to a re-center; and opt-in backlog coalescing (`fillProcessing.COALESCE_BACKLOG_REPLAY`, default off) is added. New P0 counters (`spreadCorrectionRefusedCount`, per-cause `spreadCorrectionRefusalCauses`, `spreadCorrectionRetryCount`) surface via `getMetrics()`, and the uncertain-broadcast adopt-or-defer invariant is recorded (INV-COW-010). Covered by `tests/test_spread_correction_resilience.ts` plus a settings-merge override contract.
|
|
12
|
+
|
|
13
|
+
- **Feat(credit)**: top up renewals from free collateral — a renewal previously capped the reborrow at the collateral released by the repay, so it scaled the principal down when the offer's collateral price moved even while idle collateral of the same asset was held. `useFreeCollateral` (default true, per lending item) adds the borrower's free balance of the collateral asset to the renewal budget, bounded by the position's `assignedCollateralBudget`; the accept builder treats an explicit collateral amount as a floor and tops it up to what the borrow requires while the borrow stays clamped to the budget. Deferred reborrows re-read the live free balance and position budget per retry, and the free-balance read is skipped when the released collateral already backs the reborrow. `useFreeCollateral: false` opts back into the released-only ceiling. Behavioral caveat: a renewal can now lock idle collateral, including an asset also used by the grid. Covered by new credit-runtime stages for top-up, opt-out, budget cap, switch-flow and replay refresh.
|
|
14
|
+
|
|
15
|
+
- **Feat(credit)**: report Avar. CR per borrowed credit — the single Avar. CR line value-weighted every priced deal together, so unrelated debt assets (e.g. a BTS borrow and an MPA borrow) were blended into one figure that matched neither obligation. Priced support rows are now grouped by debt asset with one value-weighted average per group, ordered by borrowed amount (largest exposure first); collateral legs within a borrowed credit still join on one line. The unused global `avgCr` is dropped (the blank-line guard simplifies to `supportedRows.length > 0`). Display-only change to `scripts/analyze-credit.ts`.
|
|
16
|
+
|
|
17
|
+
- **Fix(config)**: exclude legacy order-key aliases from the draft seed — pre-rename `activeOrders`/`reserveOrders` keys survive in `DEFAULT_CONFIG` of settings files written before the `coreOrders`/`edgeOrders` rename, and `mergeSettings` propagates them into the loaded defaults, failing the parity guard on an unclassified key. Both aliases are added to `DRAFT_EXCLUDED_KEYS` while `migrateLegacyOrderKeys` still migrates them away, so older files pass without hiding genuinely new keys.
|
|
18
|
+
|
|
19
|
+
- **Feat(cli)**: add a per-asset rich list (`dexbot rich`) — a read-only utility printing top holders of one or more assets via the chain `asset_api` (`get_asset_holders`), exposed as `dexbot rich <asset...> [--top N] [--json|--csv]` with a `richlist` npm script. It connects only to nodes that expose `asset_api` to anonymous logins, clamps `--top` to the node's advertised `api_limit_get_asset_holders`, and retries unresolved legacy `bit*` MPA names with the prefix stripped. Source-checkout-only and intentionally not advertised in the root README.
|
|
20
|
+
|
|
21
|
+
- **Fix(scripts)**: make the pool-history diagnostic fail fast and exit cleanly — `--pool` is validated against the `1.19.N` object-ID shape up front (clear message, exit 1) instead of issuing doomed RPCs that surfaced an opaque remote `uint64_t` parse error; the two invalid account-history tests are replaced by a real `get_liquidity_pool_history_by_sequence` pagination test; and `process.exit(0)` after disconnect stops the native transport's reconnect timers from hanging the script.
|
|
22
|
+
|
|
23
|
+
- **Feat(ui)**: TradingView exporter fixes and a live data-age badge — restore the accidentally dropped `1h` timeframe (aggregation stays keyed by seconds, so the `seconds >= baseIntervalSeconds` guard disables it on coarser bases); resolve the default timeframe from `payload.defaultTimeframe` in the page script (the generation-time identifier threw `ReferenceError` and drew nothing); sort candles by bucket time once at the entry point (three consumers assume ascending order) with a warn on an actual reorder; drop the noisy `· volume · uPlot` subtitle tail; and embed the newest-candle freshness anchor plus `intervalSeconds` so a readout beside the title recomputes the age every minute, fully offline (green under 24h, amber 1-7 days, red over a week). Also brighten the dynamic-weight research-panel labels and add a 16-knob factory reset button that reuses `applyParams()`.
|
|
24
|
+
|
|
25
|
+
- **Fix(bot)**: return to the Actions menu after saving a new bot — the New bot flow looped back into `promptBotData` after a successful save, immediately opening another blank Bot Editor that read as a duplicate window and hid the fact the previous bot was saved. Only the success path changes; Cancel/Esc and invalid-input paths already exited the loop.
|
|
26
|
+
|
|
27
|
+
- **Fix(order)**: treat empty-string boundary/gap as unknown geometry in the last `''`-blind guards — the earlier null/`''` hardening missed three sibling guards, so a `''` boundary could pass as finite boundary 0. `sync_engine.ts` orphan adoption now defers with `boundary-unknown-deferred`, `order.ts consumePendingFillCrawls` drops owed crawls with `null-boundary`, `validate.ts optimizeRebalanceActions` yields NaN instead of stamping a bogus boundary-0 gap-evacuation bypass, and `math.ts getSellStartIdx`/`resolveGapSlots` move the absent-aware contract into the shared helper (a genuine boundary 0 is preserved). Defense-in-depth on currently unreachable paths; covered by EVAC-021/023 and PEND-007b.
|
|
28
|
+
|
|
29
|
+
- **Perf(tests)**: cut suite wall time ~4x with a parallel runner and deterministic waits — `run-tests.ts` defaults to `min(cores, 4)` parallel files (`DEXBOT_TEST_CONCURRENCY=1` restores sequential) and preloads the ESM loader hooks for `esmMockEntry`-only and single-stage files so they no longer re-exec a second node process; fixed sleeps/busy-loops become condition-driven waits across the COW, native-subscription, fill-lifecycle, account-totals, bot-supervisor and position-manager suites; and two test-only seams default to the existing production values. A follow-up consolidates shared-mock stages into grouped units and trims the heaviest deterministic sweeps (Huber scratch-array reuse verified bit-identical, coarser entropy stride, shorter tracker prefix-parity series). Production numeric output is unchanged: 313 passed / 0 failed / 14 skipped live in ~11.4s (from ~45s sequential).
|
|
30
|
+
|
|
31
|
+
- **Chore**: replace live bot/account identifiers with placeholders in source comments, test fixtures and CHANGELOG entries (`<bot>`, `<account-name>`, synthetic `1.2.12345`, `BITSHARES_TEST_ACCOUNT*` env overrides) so no live identifier ships. Comment/string-only.
|
|
32
|
+
|
|
33
|
+
- **Docs**: highlight collapsible `<details>` summaries with `<mark>` across the sub-READMEs; add the §9 order-engine retrospective addendum for the v1.6.4→v1.6.14 arc (uncertain-broadcast and suspended-persistence deferral, fail-closed unknown geometry, pre-broadcast UPDATE-target guard) with the commit ledger and four new invariants; and record the spread-correction resilience contract across `architecture.md`, `LOGGING.md`, `COW_INVARIANTS.md` (INV-COW-010), the developer guide, `modules/README.md` and `tests/README.md`.
|
|
34
|
+
|
|
35
|
+
## [1.6.14] - 2026-10-12 - Spread-Correction Last-Fill Guard & Live Market Floor, Committed-Size Drift Resize, COW Pre-Broadcast Guards & P2 Counters, Fail-Closed Unknown Geometry, Order-Key Rename
|
|
36
|
+
|
|
37
|
+
### 2026-10-12
|
|
38
|
+
|
|
39
|
+
- **Fix(order-engine)**: never let spread correction trade through the last real fill — after a stop/start regenerated the grid, the genesis-bound LAST-FILL-GUARD pivot was wiped with the generation, and spread correction bypassed the guard, so it could place a SELL at/below (or a BUY at/above) the last real trade price. A bot-scoped last-market-fill reference (price/type/fillsAt) now survives `clearGrid()`/regeneration and is restored at startup under a 24h TTL; spread-correction candidates are filtered against it (planner + boundary promotion), failing open when no real fill is known; the LAST-FILL-GUARD bypass is denied whenever a real market reference exists, keeping the heuristic bypass only while the local snapshot is fresh; a cold book (no live order either side) skips correction and reports a structural stall so the targeted chain sync arms; and a timestamped pre-reject snapshot copy is kept before `clearGrid()`. Reference resolution is consolidated into one predicate shared by the planner and the COW bypass gate. Covered by the SMR-1..6 suite.
|
|
40
|
+
|
|
41
|
+
- **Refactor(order-engine)**: unify spread-correction trust decisions behind one readiness gate and a live market floor — the planner, the crossing filter and the COW bypass could otherwise reason from different state. `evaluateSpreadCorrectionReadiness()` is now the single pure verdict: a cold book is a hard refuse, while a stale snapshot or known-unmatched orders degrade to plan-but-withhold-the-LAST-FILL-GUARD-bypass; it returns the crossing floor and collision-filter input alongside the verdict. The coarse "is this anchor stale?" distance cap is replaced by a live order-book/ticker read on a bounded cadence, and the NEWER of the live read and the fill anchor is used as the floor so staleness is prevented at the source; candidates are filtered against known-unmatched chain price levels keyed off the data rather than the priority-ranked reason. A gate failure now refuses the cycle (correct-by-refusal) instead of planning with no floor and no collision filter. `config.timing.SPREAD_CORRECTION_SYNC_FRESH_MS` is the single trust window for both snapshot staleness and live-price refresh pacing. Covered by the SMR-1..10 suite.
|
|
42
|
+
|
|
43
|
+
- **Fix(grid)**: resize the full side when a deposit slips past the fund ratio — the 3% available-funds trigger measures `chainFree - virtual`, but the fill/rotation sizing pipeline re-derives VIRTUAL slot sizes from the live budget, so an external deposit is folded into the virtual reservation on the first rotation after it lands, the ratio stays pinned at the unallocated remainder, and the on-chain orders keep their pre-deposit sizes without ever tripping the trigger. A new `checkCommittedSizeDrift` computes each side's geometric ideal from the current budget, replays the resize's free-balance growth cap against the on-chain orders, and flags the side when the committed delta reaches `GRID_REGENERATION_PERCENTAGE` of the committed size (denominator is the committed total, not the whole allocation, so a genuine full-side undersize is not understated). Wire it into `monitorDivergence` so the maintenance runtime routes it to the COW resize path. Impact: an external deposit/withdrawal that shifts a side's budget by >=3% now resizes all of its on-chain orders on the next pipeline-empty maintenance tick instead of only the fill-generated replacements.
|
|
44
|
+
|
|
45
|
+
- **Fix(grid)**: harden committed-size drift and unify the fund trigger — each slot's counted drift is now gated on the same blockchain-integer comparison the resize uses to emit an on-chain UPDATE, so a flagged side can never drive the COW resize to a no-op and re-trigger every tick (the free-balance replay still evolves identically). The drift core is folded into `checkAndUpdateGridIfNeeded`, which becomes the complete fund trigger (available-funds ratio + over-allocation + committed drift) so the legacy ratio legs cannot be consumed or regress in isolation; `monitorDivergence` refreshes funds once and calls only the unified entry, with `_getSizingContext` split into a pure sync core shared by both legs. Partial-fill behaviour is pinned: a >=3%-of-committed remainder on an on-chain slot triggers the self-correcting full-side resize, a sub-threshold remainder stays silent.
|
|
46
|
+
|
|
47
|
+
- **Feat(order-engine)**: harden COW pre-broadcast guards and add P2 observability counters — `runPreBroadcastGuards` re-reads every UPDATE action's tracked orderId before op-building; a target already gone on chain refuses the whole batch (`UPDATE_TARGET_MISSING`), pops the working grid and requests a structural resync instead of letting `limit_order_update` abort a chunk mid-broadcast and leave a partially-applied grid (fails open on a non-Map/errored read; each candidate is re-verified once via `readSingleOrder`). A non-spread-correction CREATE/UPDATE destination inside the plan's gap band is counted and warned (never blocked — spread correction legitimately places into the band). New counter-only P2 metrics (never gating placement): `refusedCommitCount`, `orphanFillCreditedCount`, `restampBuyAboveAnchorCount`, `boundaryDriftExceedsWindowCount` (surfaced via a manager-metrics overlay in `getMetrics()`) and `gapBandPlacementShadowCount`. Covered by `tests/test_p2_observability_counters.ts` and COW-COMMIT-013..016.
|
|
48
|
+
|
|
49
|
+
- **Fix(order-engine)**: fail closed on unknown boundary/gap across gap-evacuation and COW shadow paths — an unknown boundary or gap width (`null`/`undefined`/`''`) was read as the valid value 0 via `Number(...)`, casting real geometry around slot 0 across the plan/evacuation/guard paths. Unknown geometry is now treated as unknown in `detectGapEvacuationCandidates`, `geometryTypeForSlotIndex`, `isEvacuationStampStillValid`, `stampGapEvacuationRotation`, `optimizeRebalanceActions` (and its `applyGridDivergenceCorrections` call site), `planVacatedRailRefill`, `buildCowResultFromPlan` and the `runPreBroadcastGuards` boundary fallback; a genuine boundary 0 is preserved. Covered by EVAC-005/007/016/021 (the EVAC-007 fixture is now non-vacuous).
|
|
50
|
+
|
|
51
|
+
- **Fix(order)**: close the missed 1.6.13 regressions in absent geometry and the rebuild guard — an absent geometry value was coerced by `Number()` to the valid-looking 0; the new `Format.toKnownNumber` (null/undefined/'' => NaN; a genuine 0 stays 0) backs the shadow gap, plan boundary and evac-stamp reads, `validate.reconcileGrid` no longer B-stamps a gap-0 evac on an absent plan gap, `order.consumePendingFillCrawls` falls back to the config-derived gap, and the geometry helpers keep absence detectable (SELL rail fails open). The generic LAST-FILL-GUARD no longer silently un-arms on grid regeneration while the last real fill price is still known: `resolveLastFillGuardReference` falls back to the bot-scoped last-market-fill row (read-time only, so the genesis-bound pivot/persist contract is unchanged) and is used by `runLastFillGuardCheck`, the batch freeze, `runFinalPivotGate` and the batch summary. Covered by EVAC-022 and LFP-9.
|
|
52
|
+
|
|
53
|
+
- **Fix(math)**: keep `validateBoundaryCommit` fail-closed for garbage boundaries — only `null`/`undefined`/`''` mean "no proposal" (ok); every other non-numeric value (`'abc'`, `NaN`, `Infinity`) is rejected as `non_integer_boundary` again. The 1.6.13 absent-aware rewrite had silently widened this into "garbage = no proposal", the wrong failure mode for `validatePersistedBoundary` (the disk-trust gate, where a corrupt persisted value must surface as a rejection/rebuild, never pass as absence). Contract pinned in `tests/test_boundary_restore_validation.ts`; no current caller passes a non-numeric value.
|
|
54
|
+
|
|
55
|
+
- **Refactor(config)**: rename `activeOrders` → `coreOrders` and `reserveOrders` → `edgeOrders` — aligns the persisted bot-config keys with the editor labels (CoreOrder / EdgeOrder) and finishes the edge vocabulary, which previously mixed reserve/edge/active for the same concepts, across modules, claw, tests, scripts, analysis and docs (export keys become `core_orders`/`edge_orders`; internal identifiers renamed accordingly). Pre-rename user settings are supported at a single read boundary (`migrateLegacyOrderKeys`): `loadSettingsFile` rewrites `bots.json` to canonical keys on first read, and the maintenance fingerprint/live-apply paths canonicalize raw entries. `tests/test_reserve_orders.ts` → `tests/test_edge_orders.ts` with legacy-alias, validation and on-disk-migration coverage. Behavior-preserving.
|
|
56
|
+
|
|
57
|
+
- **Refactor(modules)**: drop dead exports and trim runtime default objects — remove the unused `GRAPHENE_100_PERCENT` constant and stop exporting internal-only symbols (`equalsBytes`, `sendCredentialDaemonRequest`, `ReplayMessageFn`, `DaemonKeyStore`, `reconcileAfterUncertainBroadcastImpl`, `pollChainForConfirmation`); cut the `dexbot_cow_runtime` and `dexbot_maintenance_runtime` default export objects down to the members actually consumed by `dexbot_class` (plus `_internalDeferredHold` for tests). No runtime logic changed.
|
|
58
|
+
|
|
59
|
+
- **Perf(unlock)**: lazy-load the bot editor and chain client — `unlock`/`start` eagerly imported `account_bots` and `bitshares_client`, pulling the native chain-client module graph (~80ms) into every invocation even when the interactive onboarding path is never taken; both are now loaded only when that path is reached.
|
|
60
|
+
|
|
61
|
+
- **Fix(config)**: tolerate `process.umask` failure in worker threads — worker threads cannot set the process-wide umask (`process.umask()` throws `ERR_WORKER_UNSUPPORTED_OPERATION`), which crashed config load; the call is now skipped gracefully (matching `Runtime.umask()`'s guard) so config stays loadable in a worker.
|
|
62
|
+
|
|
63
|
+
- **Chore(tests)**: cut suite wall time and make the ESM-mock runner deterministic — ESM-mock stages now run in `worker_threads` Workers (own module registry, shared parent PID; stub files keyed by PID+threadId so concurrent stages cannot clobber one another; default concurrency `min(availableParallelism, 8)`; `runEsmMockStagesShared`/`runEsmMockStagesGrouped` consolidate same-mock stages, e.g. `test_credit_runtime`'s 55 stages in ~264ms vs ~4057ms). Sleep-dominated tests poll the real condition instead, redundant heavy crypto is dropped (`native_ecc_equivalence` 32→8 iterations, browser scrypt cross-checks at N=1024), and the market-adapter JSON cache-invalidation test forces a strictly past stamp via `utimesSync` instead of relying on mtime granularity. Full suite remains 312/312 (14 skipped live).
|
|
64
|
+
|
|
65
|
+
- **Docs**: sync linked guides with the code after a staleness audit — `COPY_ON_WRITE_MASTER_PLAN` (drop the removed `Accountant.validateTargetGrid` dry-run guardrail and describe the real planning-time budget chokepoint), `LIFECYCLE`/`FUND_MOVEMENT`/`COW_INVARIANTS` (refreshed line anchors), `architecture` (replace removed `calculateCurrentSpreadGap`/`calculateTargetSpread` with the live `calculateCurrentSpread` + `shouldFlagOutOfSpread` path), `GRID_PRICE_INVARIANT` (code-review baseline to v1.6.13), and `docs/README` (index the memu-memory/trend-detection skill packs; align the `GRID_RECALCULATION` bullet with the available-funds-resize naming). Docs-only.
|
|
66
|
+
|
|
5
67
|
## [1.6.13] - 2026-10-10 - Spread-Stall Cause Reporting & Chain Sync, Resync-Cascade Guards, Month-Shard Candle Cache, Dedup & Dead-Code Purge, npm 12 Install & PM2 Fixes
|
|
6
68
|
|
|
7
69
|
### 2026-10-10
|
|
@@ -603,7 +665,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
|
|
|
603
665
|
- **Chore(browser-boundary)**: align the browser-safe surface with reality — `package.json` browser-map exclusions added for `modules/runtime_settings.js`, all five Node-bound `bitshares-native` entry files (`transport`, `signing_client`, `subscriptions`, `tx/builder`, `tx/tx_cache`) and `market_adapter/utils/chain.js` (top-level `createRequire(import.meta.url)`); AGENTS.md Node-only list extended with the same files so convention docs match the bundler config (`package.json`, `AGENTS.md`).
|
|
604
666
|
- **Refactor(dead-code)**: remove unreferenced symbols surfaced by the audit — `constants.ts` prunes the ECC mirror block, unused timing/network constants (`SUBSCRIPTION_SILENT_THRESHOLD_MS`, `STARTUP_CONNECT_TIMEOUT_MS`, `MAX_TRANSACTION_SIZE`, `MAX_TIME_UNTIL_EXPIRATION`, `PERCENT_1`) and the supervisor `MAX_MEMORY_MB` fallback, and aligns OBJECT_TYPES with the BitShares enum (`CUSTOM_AUTHORITY` 17 … `CREDIT_DEAL` 22) adding the credit-offer/deal object types used by credit flows; `cr_planner.ts` drops the legacy CR-formula exports (`planCrAdjustment`, collateral/debt target helpers) while keeping `calculateCollateralRatio` internal; `credit_runtime.ts` removes the test-only `openCreditPosition`/`getCollateralOffsets` wrappers (renewOnly coverage retargeted to `buildCreditOfferAcceptOperation`); `key_store.ts` removes the unused `DirectKeyStore`; `crypto/index.ts` drops dead pure-primitive re-exports; `dexbot_fill_runtime.ts` collapses tautological FILL_PROCESSING.MODE comparisons (history processing unconditional, open-orders fallback gated solely on `requiresOpenOrdersSync`); `bots_file_lock.ts` fixes the writeJsonFileAtomic doc drift (`modules/constants.ts`, `modules/cr_planner.ts`, `modules/credit_runtime.ts`, `modules/key_store.ts`, `modules/crypto/index.ts`, `modules/dexbot_fill_runtime.ts`, `modules/bots_file_lock.ts`).
|
|
605
667
|
- **Test**: add regression coverage for the trickier audit fixes — `test_to_finite_number_null.ts` locks the nullable-read semantics, `test_credential_policy_layer_merge.ts` covers per-op allowedOps merging plus `__proto__` rejection, settings-merge tests cover EXPERT GRID_COMPARISON preservation and scalar-override immunity plus deep-merge `__proto__` pollution rejection at nested levels, and the fill-batch suite asserts a deferred fill restores the exact pre-call `_fillBatchInFlight` count so concurrent batches cannot zero each other's guard; fixtures updated for the removed `getSizingContext` wrapper and the signal-based abort path (`tests/test_to_finite_number_null.ts`, `tests/test_credential_policy_layer_merge.ts`, `tests/test_settings_merge.ts`, `tests/test_sync_fill_history_batch.ts`, `tests/*`).
|
|
606
|
-
- **Tune**: raise the AMA slope ceiling default 0.085 → 0.09 and narrow the research slider floor 0.04 → 0.06 — de-sensitizes the AMA trend channel by ~5.6% (factor 0.85/0.9) so grid range-scaling asymmetry, grid price offset, and buy/sell weight tilt react proportionally weaker to the same slope magnitude; applied asymmetry at the current
|
|
668
|
+
- **Tune**: raise the AMA slope ceiling default 0.085 → 0.09 and narrow the research slider floor 0.04 → 0.06 — de-sensitizes the AMA trend channel by ~5.6% (factor 0.85/0.9) so grid range-scaling asymmetry, grid price offset, and buy/sell weight tilt react proportionally weaker to the same slope magnitude; applied asymmetry at the current <market-pair> slope drops ~21.25% → ~20.1% and the AMA-slope grid-reset trigger threshold rises 0.0068 → 0.0072 %/bar; behavior unchanged at |slopePct| ≥ 0.09 (identical saturation cap), research chart paste payloads with amaS% in [0.04, 0.06) clamp up to 0.06 (`modules/constants.ts`, `analysis/trend_detection/dynamic_weight_chart_generator.ts`, `analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md`).
|
|
607
669
|
- **Fix(market-adapter)**: harden locking, signal math, and input tools from a full module review — Hurst buffer cap window+2 → window+1 so the newest candle is always included with shared `classifyHurst()` and a `HURST_STRENGTH_NORMALIZER` strength scale; ATR re-warms per chain segment so a bad candle no longer leaks pre-break values across the gap; dynamic-weight/slope dead-band boundaries inclusive on both sides with exact-zero slopes staying NEUTRAL at the default `neutralZonePct` of 0; permutation entropy validates m/delay/window against `PE_ANALYZER_LIMITS` at construction instead of running degenerate configs silently; Kalman filter defaults unified through a single `_initState()` with beams returned as a copy and null-safe displacement; a malformed custom regimeTable throws at construction instead of producing silent NaN multipliers. File locks gain an ownership token (fresh UUID per holder written into every payload; release only unlinks when the token still matches) so a stolen lock can no longer be deleted by its previous holder, including pid collisions across containers sharing a mounted volume — legacy token-less payloads stay releasable; partial acquisitions clean up their orphaned lock file instead of locking out later contenders, heartbeat derives as clamp(staleMs/2, 1s..30s) so it always fires inside the staleness window, and the holder heuristic recognizes dexbot-embedded adapters while anchoring entrypoint names to argv/path boundaries so unrelated scripts such as robot.js no longer match. Service wiring clamps clipPercentile to (0,100] at the read point, normalizes volatility exponent/scaleX to their effective ranges at the single configured point, derives amaSlopeGated/amaChannelContribution diagnostics from the canonical Kalman-disabled weight series so diagnostics agree with finalOffset whenever gating is active, records `triggerSuppressedReason=stale_candle_data` for stale-but-new cycles, and config normalizers treat null/empty as unset before `Number()` coercion so explicit JSON null no longer means "disabled". Input tools: fetch_lp_data completes the interval map (30m..7d) with loud validation instead of parsing "30m" as 30 seconds, adds linear retry backoff and honest range labels in --start/--end mode; fetch_cex_synthetic_data fixes the dead HTX endpoint (/market/history/kline), honors exchange page caps via `CEX_PAGE_LIMIT_CAPS`, corrects MEXC intervals (6h/12h/1W), rejects zero-price leg candles, and handles --help before bot resolution. Constants: new keys centralized (`FILE_LOCK_HEARTBEAT_MIN/MAX_MS`, `LP_FETCH_RETRY_BACKOFF_BASE_MS`, `CEX_PAGE_LIMIT_CAPS`, `PE_ANALYZER_LIMITS`, `HURST_STRENGTH_NORMALIZER`, `DYNAMIC_WEIGHT_KALMAN_WARMUP_BARS_DEFAULT`, `DYNAMIC_WEIGHT_KALMAN_BEAM_COUNT_DEFAULT`, `DYNAMIC_WEIGHT_VOLATILITY_EXPONENT/SCALE_X_MIN/MAX`), sourceRetries default 3 → 4; misc: kibana_client releases redirect bodies, data_discovery skips unreadable entries and dangling symlinks, asymmetric_bounds/collateral_manager share previously duplicated math, analysis/bot_key_utils delegates to the production createBotKey so unnamed bots resolve identical keys, vestigial exports removed, and 'use strict' hoisted above imports across ~90 files where it sat as a no-op (`market_adapter/**`, `modules/constants.ts`, `analysis/bot_key_utils.ts`).
|
|
608
670
|
|
|
609
671
|
### 2026-08-25
|
|
@@ -659,7 +721,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
|
|
|
659
721
|
|
|
660
722
|
- **Feat(cow)**: enforce a per-broadcast operation cap — a single COW rebalance can expand one fill batch into many more order operations (4 fills → 12 creates + 4 updates = 16 ops), so `FILL_PROCESSING.MAX_FILL_BATCH_SIZE` is a weak proxy for on-chain transaction size. `COW_PERFORMANCE.MAX_OPS_PER_BROADCAST` (default 4) now caps operations per broadcast; oversized batches are split into sequential transactions via `executeChunkedWithRetryOnUncertain`, restoring the original "N fills per broadcast" intent at the op level. An uncertain chunk failure continues broadcasting the remaining chunks (no order dropped); a definitively rejected chunk aborts the rest; the first failure is rethrown enriched with `partialOnChainState`, `chunksTotal`/`chunksFailed`/`chunksAborted`, and `broadcastedOperationCount`. Configurable via the runtime settings override chain (`runtimeCowPerformance`/`marketCowPerformance`/`botCowPerformance`). Covered by the new 463-line `test_cow_ops_per_broadcast.ts` (`modules/dexbot_cow_runtime.ts`, `modules/constants.ts`, `modules/dexbot_class.ts`, `modules/runtime_settings.ts`).
|
|
661
723
|
- **Fix(grid)**: exclude gap-band strays from divergence desired-window selection — a fund-driven boundary shift during `applyGridDivergenceCorrections` re-types the working grid, but the SPREAD GUARD keeps live on-chain orders inside the new spread band typed BUY/SELL, so the Phase-2 window selected "closest to market" slots purely by stored type+price and a stray SELL inside the new gap looked like the bottom of the sell rail and was never relocated, collapsing the real spread (boundary 107→110 left sells at 111–113 inside the new gap, real spread 0.5% vs the 2.0% target). New shared `MathUtils.isSlotInRail` (pure geometric rail-membership test) now filters desired-window candidates using the working boundary; the strategy window and virtual-slot selection delegate to the same helper, and gap-band strays become surplus → cancelled and relocated back onto the rail (`modules/order/utils/math.ts`, `modules/order/utils/system.ts`, `modules/order/strategy.ts`, `modules/order/grid_reconcile_internal.ts`, `tests/test_is_slot_in_rail.ts`, `tests/test_cow_divergence_correction.ts`, `tests/test_lp_chart.ts`).
|
|
662
|
-
- **Tune**: lower the AMA slope grid-reset threshold from 10 to 8 — the AMA slope delta trigger resets the grid when the slope swing exceeds (`AMA_SLOPE_DELTA_THRESHOLD_PERCENT`/100) × maxSlopePct. At 10 the
|
|
724
|
+
- **Tune**: lower the AMA slope grid-reset threshold from 10 to 8 — the AMA slope delta trigger resets the grid when the slope swing exceeds (`AMA_SLOPE_DELTA_THRESHOLD_PERCENT`/100) × maxSlopePct. At 10 the <market-pair> trend reversal (DOWN baseline → UP current, delta 0.0074%/bar) stayed below the 0.0085 threshold, leaving the grid scaled for the wrong direction. Lowering to 8 (threshold 0.0068%/bar) reacts to the reversal while still ignoring small slope noise (`modules/constants.ts`).
|
|
663
725
|
- **Feat(ui)**: green/red relative-scaling feedback for price inputs — the bot editor's Price Range displayed min/max as plain white, hiding whether relative scaling (x multipliers) is active. Range values now render green for "1.55x" multipliers and red for fixed prices, and `readInput` gains a colorize option so the typed input switches red → green live the moment the "x" is entered (`modules/account_bots.ts`, `modules/order/utils/system.ts`).
|
|
664
726
|
- **Fix(ui)**: clarify the GridPrice label in the bot editor — the Price section displayed the gridPrice reference as bare "Grid:", which was ambiguous next to "Start:"/"Pool:" and collided with the section "4) Grid". Renamed to "GridPrice:" (one word, matching the `gridPrice` config field name) to reflect the values it accepts (pool/book/ama/number/none) (`modules/account_bots.ts`).
|
|
665
727
|
- **Docs**: add an end-to-end lifecycle walkthrough — new `docs/LIFECYCLE.md` consolidates the startup, fill-driven (reactive), and maintenance/AMA-driven (periodic) flows into one newcomer-facing map with mermaid system-context and sequence diagrams (fill → `_incomingFillQueue` → `processFilledOrders` → Accounting SSOT → WorkingGrid COW → single atomic broadcast → persist; `_performPeriodicGridChecks` → `performPeriodicGridChecks` → `runGridMaintenance` → `executeMaintenanceLogic`), plus a cross-cutting invariants table and file map. Surfaced as the first read from README and the docs index, and added to the npm `files` array (`docs/LIFECYCLE.md`, `docs/developer_guide.md`, `docs/README.md`, `README.md`, `package.json`).
|
|
@@ -753,7 +815,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
|
|
|
753
815
|
|
|
754
816
|
### 2026-08-14
|
|
755
817
|
|
|
756
|
-
- **Feat**: add an optional bot filter to `dexbot order` — pass a bot key as a positional argument (e.g. `dexbot order
|
|
818
|
+
- **Feat**: add an optional bot filter to `dexbot order` — pass a bot key as a positional argument (e.g. `dexbot order <botKey>`) to render only that bot's persisted grid, optionally combined with `--export` for a single-bot HTML report; matching accepts the raw key, its sanitized form, or the configured name; a missing key lists available bots and suppresses skipped-candidate noise (`scripts/analyze-orders.ts`, `dexbot.ts`, `README.md`, `docs/WORKFLOW.md`).
|
|
757
819
|
|
|
758
820
|
### 2026-08-13
|
|
759
821
|
|
|
@@ -1309,7 +1371,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
|
|
|
1309
1371
|
- **Fix**: process queued price corrections on startup and in maintenance loop — corrections queued by syncFromOpenOrders (via ordersNeedingPriceCorrection) were only processed inside _consumeFillQueue, which only runs when new fills arrive. For an idle market where sync detects a price mismatch during startup, the correction sat in the queue indefinitely, stalling the pipeline. Now processed immediately after startup sync and at the start of every maintenance cycle (`modules/dexbot_class.ts:1339`, `modules/dexbot_maintenance_runtime.ts:1399`).
|
|
1310
1372
|
- **Fix**: protect committed orders from recovery sync virtualization — during UNCERTAIN broadcast and fund-invariant recovery, the full two-pass syncFromOpenOrders could virtualize orders that were correctly placed by prior successful COW commits when the chain snapshot lags behind confirmed transactions. New `_committedOrderIds` set tracked across COW commit boundaries; PASS 1 virtualization guard skips any orderId in the set (`modules/order/manager.ts`, `modules/order/sync_engine.ts`, `modules/dexbot_class.ts`, `modules/order/accounting.ts`).
|
|
1311
1373
|
- **Fix**: cancel residual ghost orders left on chain by other-side rounding — when a fill leaves a tiny residual where opposite-asset value rounds to 0 at blockchain precision, the grid slot was virtualized but the chain order was never cancelled. New `ghostOrderId` return field drains orphan cancellations via a per-session guarded set to avoid repeat attempts (`modules/dexbot_class.ts`, `modules/order/sync_engine.ts`, `tests/test_ghost_order_fix.ts`).
|
|
1312
|
-
- **Fix**: remove hardcoded
|
|
1374
|
+
- **Fix**: remove hardcoded <market-pair> defaults from analysis scripts and docs — all 6 analysis scripts now require `--bot-key` explicitly at runtime; documentation uses `EXAMPLE-BOT` placeholders instead of `<market-pair>` (`analysis/analyze_dynamic_weight.ts`, `analysis/analyze_volatility.ts`, `analysis/analyze_kalman.ts`, `analysis/analyze_regime.ts`, `analysis/analyze_regime_windows.ts`, `analysis/analyze_derivatives.ts`, `docs/*.md`, `market_adapter/README.md`).
|
|
1313
1375
|
- **Feat**: centralize AMA config resolution in bot_key_utils for analysis tools — shared `loadBotMeta`, `resolveAmaConfig` (inline > profile > built-in with preset merge, erSmoothPeriod on all paths, fast/slow swap guard), and `resolveAmaKey` extracted from individual scripts. Dynamic chart legend now shows the resolved AMA label (AMA1/AMA2/AMA3/AMA4) instead of hardcoded AMA3 (`analysis/bot_key_utils.ts`, `analysis/analyze_dynamic_weight.ts`, `analysis/analyze_tradingview.ts`, `analysis/trend_detection/dynamic_weight_chart_generator.ts`).
|
|
1314
1376
|
|
|
1315
1377
|
## [1.1.11] - 2026-07-18 - npm publish, README install options, CLI dist resolution, .npmrc ignore
|
package/README.md
CHANGED
|
@@ -246,8 +246,8 @@ Grouped exactly as the bot editor shows them (`dexbot bot` → `2) Modify bot`
|
|
|
246
246
|
| Parameter | Type | Description |
|
|
247
247
|
| :--- | :--- | :--- |
|
|
248
248
|
| **`botFunds`** | object | `Sell`/`Buy` — capital allocation: `{ sell: "100%", buy: "100%" }`. Numbers or percentage strings |
|
|
249
|
-
| **`
|
|
250
|
-
| **`
|
|
249
|
+
| **`coreOrders`** | object | `CoreOrder` — target active orders per side, counted closest to the market: `{ sell: 20, buy: 20 }` |
|
|
250
|
+
| **`edgeOrders`** | object | `EdgeOrder` — edge-pinned insurance orders resting live outside the active window, to catch fat fingers: `{ buy: 0, sell: 0 }` (`buy` pins the grid floor, `sell` the grid ceiling; `0` disables per side) |
|
|
251
251
|
|
|
252
252
|
**`6) Adapter`**
|
|
253
253
|
|
package/analysis/README.md
CHANGED
|
@@ -39,7 +39,7 @@ Tools that inspect DEXBot trading behavior and the market data it operates on. O
|
|
|
39
39
|
|
|
40
40
|
Common abbreviations used throughout: OHLC, AMA, ER, ATR, Kalman, Hurst, PE, R, LIFO, FIFO, PnL, SMA, VWMA. Full definitions below.
|
|
41
41
|
|
|
42
|
-
<details><summary>Abbreviation glossary (click to expand)</summary>
|
|
42
|
+
<details><summary><mark>Abbreviation glossary (click to expand)</mark></summary>
|
|
43
43
|
|
|
44
44
|
| Term | Full name | Plain English |
|
|
45
45
|
|------|-----------|---------------|
|
|
@@ -163,7 +163,7 @@ node dist/analysis/trade_profitability.js 1.2.123456 \
|
|
|
163
163
|
--hours 168 --match-mode fifo
|
|
164
164
|
```
|
|
165
165
|
|
|
166
|
-
<details><summary>Options (click to expand)</summary>
|
|
166
|
+
<details><summary><mark>Options (click to expand)</mark></summary>
|
|
167
167
|
|
|
168
168
|
| Flag | Default | Description |
|
|
169
169
|
|------|---------|-------------|
|
|
@@ -208,7 +208,7 @@ node dist/analysis/trade_profitability.js 1.2.123456 \
|
|
|
208
208
|
|
|
209
209
|
**Metrics glossary** — `R` = the size of the average losing trade. A +3R trade earned 3× what a typical loser costs you.
|
|
210
210
|
|
|
211
|
-
<details><summary>Per-metric definitions (click to expand)</summary>
|
|
211
|
+
<details><summary><mark>Per-metric definitions (click to expand)</mark></summary>
|
|
212
212
|
|
|
213
213
|
| Output line | Meaning |
|
|
214
214
|
|-------------|---------|
|
|
@@ -278,7 +278,7 @@ npm run analysis:grid-check -- --bot-key <bot-key> --hours 168 --increment 0.5
|
|
|
278
278
|
|
|
279
279
|
Exit code `0` = pass, `2` = violations found, `1` = fatal error. Bot keys resolve via `profiles/bots.json` (`--list-bots` to enumerate); the account defaults to the bot's stored `accountId` when present (no chain lookup — the ID is auto-saved next to `preferredAccount` after the first successful name resolution, re-verified with `--refresh-account`), otherwise `preferredAccount` is resolved on-chain, and can be overridden with `--account <1.2.x|name>`.
|
|
280
280
|
|
|
281
|
-
<details><summary>Options (click to expand)</summary>
|
|
281
|
+
<details><summary><mark>Options (click to expand)</mark></summary>
|
|
282
282
|
|
|
283
283
|
| Flag | Default | Description |
|
|
284
284
|
|------|---------|-------------|
|
|
@@ -319,7 +319,7 @@ node dist/analysis/analyze_trade_heatmap.js \
|
|
|
319
319
|
--slice-months 6
|
|
320
320
|
```
|
|
321
321
|
|
|
322
|
-
<details><summary>Options (click to expand)</summary>
|
|
322
|
+
<details><summary><mark>Options (click to expand)</mark></summary>
|
|
323
323
|
|
|
324
324
|
| Flag | Default | Description |
|
|
325
325
|
|------|---------|-------------|
|
|
@@ -429,7 +429,7 @@ Shared analyzers and chart renderers for the dynamic-weight signal path. Core en
|
|
|
429
429
|
- [README.md](trend_detection/README.md) — directory overview and module index
|
|
430
430
|
- [DYNAMIC_WEIGHT_RESEARCH.md](trend_detection/DYNAMIC_WEIGHT_RESEARCH.md) — AMA+Kalman blend with Hurst/PE regime gating, formula reference, knob guide
|
|
431
431
|
|
|
432
|
-
<details><summary>Modules (click to expand)</summary>
|
|
432
|
+
<details><summary><mark>Modules (click to expand)</mark></summary>
|
|
433
433
|
|
|
434
434
|
| Module | Purpose |
|
|
435
435
|
|--------|---------|
|
|
@@ -34,7 +34,7 @@ The sections below cover manual usage (explicit candle files, direct runner flag
|
|
|
34
34
|
## What It Produces
|
|
35
35
|
|
|
36
36
|
- Log-scale price chart
|
|
37
|
-
- Candle timeframe buttons: `1h`, `4h`, `1d`, `1w`
|
|
37
|
+
- Candle timeframe buttons: `1h`, `4h`, `1d`, `1w`, `1M`
|
|
38
38
|
- Pair-orientation switcher for `A/B` and `B/A`
|
|
39
39
|
- SMA overlay
|
|
40
40
|
- AMA preset buttons `1–4` (one-click AMA1–4, active preset highlighted); numeric inputs kept
|
|
@@ -48,6 +48,7 @@ The sections below cover manual usage (explicit candle files, direct runner flag
|
|
|
48
48
|
- Volume badge (bottom-right of the volume chart, same small type): visible-window max volume, always with the currency suffix (`1.2M BTS`); click the badge, the legend `Vol` value, or the toolbar unit button to switch base/quote units (quote ≈ base × close, persisted per chart like the AMA settings; feed charts show publish counts and disable the switch)
|
|
49
49
|
- Bottom volume panel with `Volume` toggle and per-bar hover tooltip
|
|
50
50
|
- Crosshair legend with current candle values
|
|
51
|
+
- Live data-age badge next to the title: the age of the newest candle is recomputed every minute in the browser (minutes under an hour, hours and minutes under a day, days and hours beyond), so a chart saved or opened later shows its own staleness — green under 24h, amber 1–7 days, red over a week (unknown when the source carries no candle time or `meta.updatedAt`)
|
|
51
52
|
|
|
52
53
|
## Quick Start
|
|
53
54
|
|
package/claw/README.md
CHANGED
|
@@ -43,7 +43,7 @@ npm install
|
|
|
43
43
|
|
|
44
44
|
## Files
|
|
45
45
|
|
|
46
|
-
<details><summary>Module and file map (click to expand)</summary>
|
|
46
|
+
<details><summary><mark>Module and file map (click to expand)</mark></summary>
|
|
47
47
|
|
|
48
48
|
- Core BitShares runtime: `modules/bitshares_client.ts`, `modules/chain_queries.ts`, `modules/chain_broadcast.ts`, `modules/chain_actions.ts`
|
|
49
49
|
- Strategy and state helpers: `modules/short_mpa_strategy.ts`, `modules/position_manager.ts`, `modules/position_manager_watch.ts`
|
|
@@ -188,7 +188,7 @@ Shared boundary notes live in `skills/shared/references/skill-boundaries.md`.
|
|
|
188
188
|
| NullClaw | `SKILL.toml` skill manifest plus MCP server config | Zig-native workspace assistant with manifest loading | Strong fit for local workspace loading, but more dependent on NullClaw-specific config conventions |
|
|
189
189
|
| memU | Subprocess bridge plus MCP server | Proactive memory and intent capture for AI agents | Python-based memory framework with LLM-powered extraction and vector search |
|
|
190
190
|
|
|
191
|
-
<details><summary>Quick selection rule of thumb (click to expand)</summary>
|
|
191
|
+
<details><summary><mark>Quick selection rule of thumb (click to expand)</mark></summary>
|
|
192
192
|
|
|
193
193
|
- Choose **OpenClaw** for the broadest assistant platform.
|
|
194
194
|
- Choose **Hermes** if you want a general-purpose assistant with memory, messaging, cron, and browser tooling that can also trade through Claw.
|
|
@@ -271,7 +271,7 @@ npm run openfang:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT"
|
|
|
271
271
|
|
|
272
272
|
OpenFang uses the same shared bridge surface through a local CLI wrapper.
|
|
273
273
|
|
|
274
|
-
<details><summary>Compatibility command surface (click to expand)</summary>
|
|
274
|
+
<details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
|
|
275
275
|
|
|
276
276
|
```bash
|
|
277
277
|
npm run openfang:bridge -- manifest
|
|
@@ -338,7 +338,7 @@ npm run nanoclaw:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT"
|
|
|
338
338
|
|
|
339
339
|
NanoClaw already ships its own `claw` skill, so keep this bridge skill named `bitshares-claw`.
|
|
340
340
|
|
|
341
|
-
<details><summary>Compatibility command surface (click to expand)</summary>
|
|
341
|
+
<details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
|
|
342
342
|
|
|
343
343
|
```bash
|
|
344
344
|
npm run nanoclaw:bridge -- manifest
|
|
@@ -359,7 +359,7 @@ DEXBOT_ROOT="$(cd .. && pwd)"
|
|
|
359
359
|
npm run zeroclaw:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT" --output ~/.zeroclaw/workspace/skills/ai-bots/SKILL.toml
|
|
360
360
|
```
|
|
361
361
|
|
|
362
|
-
<details><summary>Compatibility command surface (click to expand)</summary>
|
|
362
|
+
<details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
|
|
363
363
|
|
|
364
364
|
```bash
|
|
365
365
|
npm run zeroclaw:bridge -- manifest
|
|
@@ -383,7 +383,7 @@ DEXBOT_ROOT="$(cd .. && pwd)"
|
|
|
383
383
|
npm run nullclaw:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT" --output ~/.nullclaw/workspace/skills/bitshares-claw/SKILL.toml
|
|
384
384
|
```
|
|
385
385
|
|
|
386
|
-
<details><summary>Compatibility command surface (click to expand)</summary>
|
|
386
|
+
<details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
|
|
387
387
|
|
|
388
388
|
```bash
|
|
389
389
|
npm run nullclaw:bridge -- manifest
|
|
@@ -435,7 +435,7 @@ mcp_servers:
|
|
|
435
435
|
args: ["/absolute/path/to/DEXBot2/dist/claw/scripts/memu_mcp_server.js", "--memu-dir", "/absolute/path/to/claw/data/memu"]
|
|
436
436
|
```
|
|
437
437
|
|
|
438
|
-
<details><summary>Compatibility command surface (click to expand)</summary>
|
|
438
|
+
<details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
|
|
439
439
|
|
|
440
440
|
```bash
|
|
441
441
|
# Via claw bridge
|
|
@@ -282,7 +282,7 @@ The bot-specific state Claw already owns and passes through the infrastructure l
|
|
|
282
282
|
type BotState = {
|
|
283
283
|
botId: string;
|
|
284
284
|
name: string;
|
|
285
|
-
|
|
285
|
+
coreOrders?: number;
|
|
286
286
|
incrementPercent?: number;
|
|
287
287
|
targetSpreadPercent?: number;
|
|
288
288
|
weightDistribution?: { sell: number; buy: number };
|
|
@@ -15,7 +15,7 @@ Keep these structural settings static in normal operation:
|
|
|
15
15
|
|
|
16
16
|
- `incrementPercent`
|
|
17
17
|
- `targetSpreadPercent`
|
|
18
|
-
- `
|
|
18
|
+
- `coreOrders`
|
|
19
19
|
|
|
20
20
|
These settings define ladder geometry and order-size distribution, so changing them is a retune, not a tactical response.
|
|
21
21
|
|
|
@@ -99,7 +99,7 @@ This is how much of each side's available balance gets committed.
|
|
|
99
99
|
- leaving reserve gives you flexibility for fees, manual intervention, and regime changes
|
|
100
100
|
- if orders get too small, reduce commitment or reduce order count
|
|
101
101
|
|
|
102
|
-
### `
|
|
102
|
+
### `coreOrders`
|
|
103
103
|
|
|
104
104
|
This is the number of live orders kept near the market on each side.
|
|
105
105
|
|
|
@@ -147,7 +147,7 @@ The clean mental model is:
|
|
|
147
147
|
- `targetSpreadPercent` controls the empty buffer
|
|
148
148
|
- `weightDistribution` controls size concentration
|
|
149
149
|
- `botFunds` controls risk budget
|
|
150
|
-
- `
|
|
150
|
+
- `coreOrders` controls depth
|
|
151
151
|
|
|
152
152
|
## When to adjust
|
|
153
153
|
|
|
@@ -210,7 +210,7 @@ For a conservative starting point:
|
|
|
210
210
|
|
|
211
211
|
- `incrementPercent: 0.5`
|
|
212
212
|
- `targetSpreadPercent: 2.0`
|
|
213
|
-
- `
|
|
213
|
+
- `coreOrders: 20 / 20`
|
|
214
214
|
- `weightDistribution: 0.5 / 0.5`
|
|
215
215
|
- `minPrice` and `maxPrice`: as narrow as the expected drift allows, not blindly `3x`
|
|
216
216
|
|
|
@@ -103,10 +103,14 @@ function botSettingsPatchSchema(description: string | null = null) {
|
|
|
103
103
|
return objectSchema({
|
|
104
104
|
patch: strictObjectSchema({
|
|
105
105
|
active: booleanSchema('Whether the bot is active'),
|
|
106
|
-
|
|
107
|
-
buy: integerSchema('Buy-side
|
|
108
|
-
sell: integerSchema('Sell-side
|
|
109
|
-
}, [], 'Per-side
|
|
106
|
+
coreOrders: strictObjectSchema({
|
|
107
|
+
buy: integerSchema('Buy-side core order count'),
|
|
108
|
+
sell: integerSchema('Sell-side core order count')
|
|
109
|
+
}, [], 'Per-side core window order counts'),
|
|
110
|
+
edgeOrders: strictObjectSchema({
|
|
111
|
+
buy: integerSchema('Buy-side edge order count'),
|
|
112
|
+
sell: integerSchema('Sell-side edge order count')
|
|
113
|
+
}, [], 'Per-side edge-pinned reserve order counts'),
|
|
110
114
|
assetA: stringSchema('Base asset symbol'),
|
|
111
115
|
assetAId: stringSchema('Base asset id'),
|
|
112
116
|
assetB: stringSchema('Quote asset symbol'),
|
|
@@ -8,6 +8,7 @@ import { PATHS } from '../../modules/paths.js';
|
|
|
8
8
|
import { writeJsonFileAtomic as baseWriteJsonFileAtomic } from '../../modules/bots_file_lock.js';
|
|
9
9
|
import { acquireFileLock } from '../../market_adapter/utils/file_lock.js';
|
|
10
10
|
import { assertNoDuplicateBotKeys, normalizeBotEntry } from '../../modules/bot_settings.js';
|
|
11
|
+
import { migrateLegacyOrderKeys } from '../../modules/bot_defaults.js';
|
|
11
12
|
import { BOT_LIVE_CONFIG_KEYS } from '../../modules/runtime_settings.js';
|
|
12
13
|
import { clone } from './utils.js';
|
|
13
14
|
import { createBotKey, sanitizeKey } from '../../modules/account_orders.js';
|
|
@@ -24,7 +25,7 @@ const DEFAULT_MARKET_PROFILES_FILE = 'market_profiles.json';
|
|
|
24
25
|
const DEFAULT_ORDERS_DIR = 'orders';
|
|
25
26
|
|
|
26
27
|
const KNOWN_BOT_KEYS = new Set([
|
|
27
|
-
'active', '
|
|
28
|
+
'active', 'coreOrders', 'edgeOrders', 'assetA', 'assetAId', 'assetB', 'assetBId',
|
|
28
29
|
'botFunds', 'debtPolicy', 'dryRun', 'gridPrice',
|
|
29
30
|
'incrementPercent', 'maxPrice',
|
|
30
31
|
'minPrice', 'name', 'preferredAccount', 'startPrice', 'strategy',
|
|
@@ -35,7 +36,8 @@ const KNOWN_BOT_KEYS = new Set([
|
|
|
35
36
|
const BOT_SETTINGS_READ_ONLY_KEYS = new Set(['botIndex', 'botKey']);
|
|
36
37
|
const BOT_SETTINGS_TRIGGER_KEYS = new Set([
|
|
37
38
|
'active',
|
|
38
|
-
'
|
|
39
|
+
'coreOrders',
|
|
40
|
+
'edgeOrders',
|
|
39
41
|
'assetA',
|
|
40
42
|
'assetAId',
|
|
41
43
|
'assetB',
|
|
@@ -59,7 +61,8 @@ const REQUIRED_BOT_KEY_ALIASES = {
|
|
|
59
61
|
};
|
|
60
62
|
|
|
61
63
|
const BOT_SETTINGS_NESTED_KEYS = Object.freeze({
|
|
62
|
-
|
|
64
|
+
coreOrders: new Set(['buy', 'sell']),
|
|
65
|
+
edgeOrders: new Set(['buy', 'sell']),
|
|
63
66
|
botFunds: new Set(['buy', 'sell']),
|
|
64
67
|
weightDistribution: new Set(['buy', 'sell'])
|
|
65
68
|
});
|
|
@@ -211,7 +214,7 @@ function cloneBotSettings(value: any) {
|
|
|
211
214
|
* Fills missing fields from DEFAULT_CONFIG and clamps values within bounds.
|
|
212
215
|
*/
|
|
213
216
|
function normalizeBotSettings(bot: Partial<BotSettings> = {}) {
|
|
214
|
-
const normalized = cloneBotSettings(bot) || {};
|
|
217
|
+
const normalized = migrateLegacyOrderKeys(cloneBotSettings(bot) || {});
|
|
215
218
|
|
|
216
219
|
normalized.active = normalizeBooleanField(normalized.active, DEFAULT_CONFIG.active);
|
|
217
220
|
normalized.dryRun = normalizeBooleanField(normalized.dryRun, DEFAULT_CONFIG.dryRun);
|
|
@@ -233,15 +236,25 @@ function normalizeBotSettings(bot: Partial<BotSettings> = {}) {
|
|
|
233
236
|
...cloneBotSettings(DEFAULT_CONFIG.botFunds),
|
|
234
237
|
...(isPlainObject(normalized.botFunds) ? normalized.botFunds : {})
|
|
235
238
|
};
|
|
236
|
-
normalized.
|
|
237
|
-
...cloneBotSettings(DEFAULT_CONFIG.
|
|
238
|
-
...(isPlainObject(normalized.
|
|
239
|
+
normalized.coreOrders = {
|
|
240
|
+
...cloneBotSettings(DEFAULT_CONFIG.coreOrders),
|
|
241
|
+
...(isPlainObject(normalized.coreOrders) ? normalized.coreOrders : {})
|
|
242
|
+
};
|
|
243
|
+
// Legacy numeric form migrates to `{ buy: n, sell: 0 }` before the default
|
|
244
|
+
// merge (mirrors the shared runtime resolver).
|
|
245
|
+
if (typeof normalized.edgeOrders === 'number') {
|
|
246
|
+
normalized.edgeOrders = { buy: Math.max(0, Math.floor(normalized.edgeOrders)), sell: 0 };
|
|
247
|
+
}
|
|
248
|
+
normalized.edgeOrders = {
|
|
249
|
+
...cloneBotSettings(DEFAULT_CONFIG.edgeOrders),
|
|
250
|
+
...(isPlainObject(normalized.edgeOrders) ? normalized.edgeOrders : {})
|
|
239
251
|
};
|
|
240
252
|
return normalized;
|
|
241
253
|
}
|
|
242
254
|
|
|
243
255
|
function mergeBotSettingsPatch(currentBot: Record<string, any> = {}, patch: Record<string, any> = {}) {
|
|
244
|
-
const next = cloneBotSettings(currentBot) || {};
|
|
256
|
+
const next = migrateLegacyOrderKeys(cloneBotSettings(currentBot) || {});
|
|
257
|
+
patch = migrateLegacyOrderKeys({ ...patch });
|
|
245
258
|
const patchKeys = Object.keys(patch || {});
|
|
246
259
|
|
|
247
260
|
for (const key of patchKeys) {
|
|
@@ -250,7 +263,7 @@ function mergeBotSettingsPatch(currentBot: Record<string, any> = {}, patch: Reco
|
|
|
250
263
|
continue;
|
|
251
264
|
}
|
|
252
265
|
|
|
253
|
-
if (['weightDistribution', 'botFunds', '
|
|
266
|
+
if (['weightDistribution', 'botFunds', 'coreOrders', 'edgeOrders'].includes(key) && isPlainObject(value)) {
|
|
254
267
|
next[key] = {
|
|
255
268
|
...(isPlainObject(next[key]) ? next[key] : {}),
|
|
256
269
|
...value
|
|
@@ -410,22 +423,48 @@ function validateBotSettingsValue(field: any, value: any, errors: any[]) {
|
|
|
410
423
|
}
|
|
411
424
|
break;
|
|
412
425
|
|
|
413
|
-
case '
|
|
426
|
+
case 'coreOrders':
|
|
414
427
|
if (!isPlainObject(value)) {
|
|
415
|
-
push('
|
|
428
|
+
push('coreOrders must be an object with sell and buy');
|
|
416
429
|
break;
|
|
417
430
|
}
|
|
418
|
-
validateNestedBotSettingKeys('
|
|
431
|
+
validateNestedBotSettingKeys('coreOrders', value, errors);
|
|
419
432
|
for (const side of ['sell', 'buy']) {
|
|
420
433
|
const sideValue = value[side];
|
|
421
434
|
if (sideValue === undefined) {
|
|
422
435
|
continue;
|
|
423
436
|
}
|
|
424
437
|
if (!Number.isInteger(Number(sideValue)) || Number(sideValue) < 0) {
|
|
425
|
-
push(`
|
|
438
|
+
push(`coreOrders.${side} must be an integer greater than or equal to 0`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
break;
|
|
442
|
+
|
|
443
|
+
case 'edgeOrders': {
|
|
444
|
+
// Legacy numeric form is accepted and migrated at read time.
|
|
445
|
+
const edgeValue = typeof value === 'number'
|
|
446
|
+
? { buy: value, sell: 0 }
|
|
447
|
+
: value;
|
|
448
|
+
if (typeof value === 'number' && (!Number.isInteger(value) || value < 0)) {
|
|
449
|
+
push('edgeOrders numeric form must be a non-negative integer');
|
|
450
|
+
break;
|
|
451
|
+
}
|
|
452
|
+
if (!isPlainObject(edgeValue)) {
|
|
453
|
+
push('edgeOrders must be an object with sell and buy');
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
validateNestedBotSettingKeys('edgeOrders', edgeValue, errors);
|
|
457
|
+
for (const side of ['sell', 'buy']) {
|
|
458
|
+
const sideValue = edgeValue[side];
|
|
459
|
+
if (sideValue === undefined) {
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (!Number.isInteger(Number(sideValue)) || Number(sideValue) < 0) {
|
|
463
|
+
push(`edgeOrders.${side} must be an integer greater than or equal to 0`);
|
|
426
464
|
}
|
|
427
465
|
}
|
|
428
466
|
break;
|
|
467
|
+
}
|
|
429
468
|
|
|
430
469
|
case 'debtPolicy':
|
|
431
470
|
if (value !== undefined && value !== null && typeof value !== 'object') {
|
|
@@ -470,6 +509,9 @@ function validateBotSettingsValue(field: any, value: any, errors: any[]) {
|
|
|
470
509
|
function validateBotSettingsState(bot: Record<string, any> = {}) {
|
|
471
510
|
const errors: string[] = [];
|
|
472
511
|
const warnings = [];
|
|
512
|
+
// Legacy key aliases collapse before validation so a pre-rename entry is
|
|
513
|
+
// neither rejected nor reported as an unrecognized key.
|
|
514
|
+
bot = migrateLegacyOrderKeys({ ...bot });
|
|
473
515
|
|
|
474
516
|
for (const field of Object.keys(BOT_SETTINGS_NESTED_KEYS)) {
|
|
475
517
|
if (bot[field] !== undefined) {
|
|
@@ -539,7 +581,6 @@ function validateBotSettingsState(bot: Record<string, any> = {}) {
|
|
|
539
581
|
function validateBotSettingsPatch(patch: Record<string, any> = {}, currentBot: Record<string, any> = {}, options: Partial<ProfileOptions> = {}) {
|
|
540
582
|
const errors: string[] = [];
|
|
541
583
|
const warnings = [];
|
|
542
|
-
const patchKeys = Object.keys(patch || {});
|
|
543
584
|
const allowUnknownKeys = Boolean(options.allowUnknownKeys);
|
|
544
585
|
|
|
545
586
|
if (!isPlainObject(patch)) {
|
|
@@ -553,6 +594,9 @@ function validateBotSettingsPatch(patch: Record<string, any> = {}, currentBot: R
|
|
|
553
594
|
};
|
|
554
595
|
}
|
|
555
596
|
|
|
597
|
+
patch = migrateLegacyOrderKeys({ ...patch });
|
|
598
|
+
const patchKeys = Object.keys(patch);
|
|
599
|
+
|
|
556
600
|
for (const key of patchKeys) {
|
|
557
601
|
if (!KNOWN_BOT_KEYS.has(key)) {
|
|
558
602
|
if (allowUnknownKeys) {
|
|
@@ -563,7 +607,7 @@ function validateBotSettingsPatch(patch: Record<string, any> = {}, currentBot: R
|
|
|
563
607
|
continue;
|
|
564
608
|
}
|
|
565
609
|
|
|
566
|
-
if (['weightDistribution', 'botFunds', '
|
|
610
|
+
if (['weightDistribution', 'botFunds', 'coreOrders', 'edgeOrders'].includes(key) && isPlainObject(patch[key])) {
|
|
567
611
|
validateNestedBotSettingKeys(key, patch[key], errors);
|
|
568
612
|
const mergedField = {
|
|
569
613
|
...(isPlainObject(currentBot[key]) ? currentBot[key] : {}),
|
package/claw/modules/types.ts
CHANGED
|
@@ -97,7 +97,8 @@ export interface ClawBridgeOptions {
|
|
|
97
97
|
|
|
98
98
|
export interface BotSettings {
|
|
99
99
|
active?: boolean;
|
|
100
|
-
|
|
100
|
+
coreOrders?: { sell?: number; buy?: number };
|
|
101
|
+
edgeOrders?: number | { sell?: number; buy?: number };
|
|
101
102
|
assetA?: string;
|
|
102
103
|
assetAId?: string;
|
|
103
104
|
assetB?: string;
|
package/claw/package.json
CHANGED
|
@@ -11,7 +11,7 @@ Covers the trading concepts available through the claw bridge, the mechanics of
|
|
|
11
11
|
|
|
12
12
|
The practical control model is split into:
|
|
13
13
|
|
|
14
|
-
- structural settings that are usually kept fixed (`incrementPercent`, `targetSpreadPercent`, `
|
|
14
|
+
- structural settings that are usually kept fixed (`incrementPercent`, `targetSpreadPercent`, `coreOrders`)
|
|
15
15
|
- adaptive settings layered on top of AMA (`weightDistribution`, min/max range ratio, debt/collateral actions)
|
|
16
16
|
|
|
17
17
|
## Reference Files
|