dexbot 1.6.13 → 1.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +2 -2
  3. package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
  4. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  5. package/claw/modules/claw_catalog.ts +8 -4
  6. package/claw/modules/dexbot_profiles.ts +59 -15
  7. package/claw/modules/types.ts +2 -1
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/skills/margin-trading/SKILL.md +1 -1
  12. package/claw/skills/margin-trading/references/position-management.md +1 -1
  13. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +25 -25
  14. package/dist/modules/account_bots.d.ts +7 -6
  15. package/dist/modules/account_bots.js +10 -10
  16. package/dist/modules/account_orders.d.ts +36 -4
  17. package/dist/modules/account_orders.js +76 -5
  18. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  19. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  20. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  21. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  22. package/dist/modules/bot_defaults.d.ts +16 -2
  23. package/dist/modules/bot_defaults.js +34 -8
  24. package/dist/modules/bot_settings.d.ts +4 -0
  25. package/dist/modules/bot_settings.js +55 -21
  26. package/dist/modules/config.js +6 -1
  27. package/dist/modules/constants.d.ts +7 -5
  28. package/dist/modules/constants.js +12 -5
  29. package/dist/modules/dexbot_class.d.ts +5 -0
  30. package/dist/modules/dexbot_class.js +8 -3
  31. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  32. package/dist/modules/dexbot_cow_runtime.js +331 -46
  33. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  34. package/dist/modules/dexbot_credential_client.js +1 -1
  35. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  36. package/dist/modules/dexbot_fill_runtime.js +12 -1
  37. package/dist/modules/dexbot_maintenance_runtime.d.ts +18 -80
  38. package/dist/modules/dexbot_maintenance_runtime.js +57 -68
  39. package/dist/modules/dexbot_startup_runtime.js +12 -0
  40. package/dist/modules/dexbot_state_recovery.js +16 -0
  41. package/dist/modules/key_store.d.ts +0 -5
  42. package/dist/modules/key_store.js +1 -1
  43. package/dist/modules/order/accounting.js +11 -11
  44. package/dist/modules/order/export.js +2 -2
  45. package/dist/modules/order/format.d.ts +15 -1
  46. package/dist/modules/order/format.js +19 -1
  47. package/dist/modules/order/genesis_policy.d.ts +1 -1
  48. package/dist/modules/order/genesis_policy.js +1 -1
  49. package/dist/modules/order/grid.d.ts +23 -11
  50. package/dist/modules/order/grid.js +383 -51
  51. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  52. package/dist/modules/order/grid_reconcile.js +5 -5
  53. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  54. package/dist/modules/order/index.d.ts +34 -8
  55. package/dist/modules/order/logger.js +2 -2
  56. package/dist/modules/order/manager.d.ts +9 -2
  57. package/dist/modules/order/manager.js +58 -24
  58. package/dist/modules/order/strategy.d.ts +2 -2
  59. package/dist/modules/order/strategy.js +51 -21
  60. package/dist/modules/order/sync_engine.js +4 -0
  61. package/dist/modules/order/utils/math.d.ts +3 -3
  62. package/dist/modules/order/utils/math.js +38 -27
  63. package/dist/modules/order/utils/order.d.ts +58 -58
  64. package/dist/modules/order/utils/order.js +119 -102
  65. package/dist/modules/order/utils/system.d.ts +193 -6
  66. package/dist/modules/order/utils/system.js +392 -29
  67. package/dist/modules/order/utils/validate.js +26 -4
  68. package/dist/modules/runtime_settings.d.ts +1 -1
  69. package/dist/modules/runtime_settings.js +3 -3
  70. package/dist/modules/types.d.ts +48 -4
  71. package/dist/scripts/analyze-orders.d.ts +1 -1
  72. package/dist/scripts/analyze-orders.js +4 -4
  73. package/dist/scripts/divergence-calc.js +6 -6
  74. package/dist/scripts/validate_bots.d.ts +1 -1
  75. package/dist/scripts/validate_bots.js +3 -3
  76. package/dist/unlock.js +7 -2
  77. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  78. package/docs/COW_INVARIANTS.md +6 -6
  79. package/docs/DEXBOT_COMPARISON.md +5 -5
  80. package/docs/EVOLUTION.md +8 -7
  81. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  82. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  83. package/docs/GRID_RECALCULATION.md +4 -1
  84. package/docs/GRID_RECONCILE.md +4 -4
  85. package/docs/LIFECYCLE.md +11 -11
  86. package/docs/LOGGING.md +14 -0
  87. package/docs/MPA_CREDIT_USAGE.md +1 -1
  88. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  89. package/docs/README.md +3 -3
  90. package/docs/architecture.md +6 -6
  91. package/docs/developer_guide.md +7 -2
  92. package/package.json +1 -1
  93. package/tests/README.md +1 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,38 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [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
6
+
7
+ ### 2026-10-12
8
+
9
+ - **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.
10
+
11
+ - **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.
12
+
13
+ - **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.
14
+
15
+ - **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.
16
+
17
+ - **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.
18
+
19
+ - **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).
20
+
21
+ - **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.
22
+
23
+ - **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.
24
+
25
+ - **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.
26
+
27
+ - **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.
28
+
29
+ - **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.
30
+
31
+ - **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.
32
+
33
+ - **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).
34
+
35
+ - **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.
36
+
5
37
  ## [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
38
 
7
39
  ### 2026-10-10
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
- | **`activeOrders`** | object | `MarketOrder` — target active orders per side, counted closest to the market: `{ sell: 20, buy: 20 }` |
250
- | **`reserveOrders`** | 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) |
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
 
@@ -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
- activeOrders?: number;
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
- - `activeOrders`
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
- ### `activeOrders`
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
- - `activeOrders` controls depth
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
- - `activeOrders: 20 / 20`
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
- activeOrders: strictObjectSchema({
107
- buy: integerSchema('Buy-side active order count'),
108
- sell: integerSchema('Sell-side active order count')
109
- }, [], 'Per-side active order counts'),
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', 'activeOrders', 'assetA', 'assetAId', 'assetB', 'assetBId',
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
- 'activeOrders',
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
- activeOrders: new Set(['buy', 'sell']),
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.activeOrders = {
237
- ...cloneBotSettings(DEFAULT_CONFIG.activeOrders),
238
- ...(isPlainObject(normalized.activeOrders) ? normalized.activeOrders : {})
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', 'activeOrders'].includes(key) && isPlainObject(value)) {
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 'activeOrders':
426
+ case 'coreOrders':
414
427
  if (!isPlainObject(value)) {
415
- push('activeOrders must be an object with sell and buy');
428
+ push('coreOrders must be an object with sell and buy');
416
429
  break;
417
430
  }
418
- validateNestedBotSettingKeys('activeOrders', value, errors);
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(`activeOrders.${side} must be an integer greater than or equal to 0`);
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', 'activeOrders'].includes(key) && isPlainObject(patch[key])) {
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] : {}),
@@ -97,7 +97,8 @@ export interface ClawBridgeOptions {
97
97
 
98
98
  export interface BotSettings {
99
99
  active?: boolean;
100
- activeOrders?: { sell?: number; buy?: number };
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.13",
3
+ "version": "1.6.14",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
@@ -2,7 +2,7 @@
2
2
  "id": "bitshares-claw",
3
3
  "name": "BitShares Claw",
4
4
  "description": "Native BitShares and DEXBot2 tools from the DEXBot2 claw integration",
5
- "version": "1.6.13",
5
+ "version": "1.6.14",
6
6
  "skills": [
7
7
  "skills"
8
8
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bitshares-claw-openclaw-plugin",
3
3
  "private": true,
4
- "version": "1.6.13",
4
+ "version": "1.6.14",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -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`, `activeOrders`)
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
@@ -75,7 +75,7 @@ These should stay static unless you intentionally retune the bot for a different
75
75
 
76
76
  - `incrementPercent`
77
77
  - `targetSpreadPercent`
78
- - `activeOrders`
78
+ - `coreOrders`
79
79
 
80
80
  These settings define the ladder geometry:
81
81
 
@@ -2637,8 +2637,8 @@ function generateHTML(data, title = 'TradingView Style Research') {
2637
2637
  // Spread = best buy/best sell gap.
2638
2638
  // Pair-aware: order prices invert (1/p) with the candles so B/A shows
2639
2639
  // the same levels in display units (side colors preserved).
2640
- let reserveLine = null;
2641
- let reserveLabel = null;
2640
+ let edgeLine = null;
2641
+ let edgeLabel = null;
2642
2642
  let ceilingLine = null;
2643
2643
  let ceilingLabel = null;
2644
2644
  let spreadMidLabel = null;
@@ -2670,7 +2670,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
2670
2670
  return (overRect.top - rootRect.top) + (1 - frac) * overRect.height;
2671
2671
  }
2672
2672
  function hideOverlayNodes() {
2673
- [reserveLine, reserveLabel, ceilingLine, ceilingLabel, spreadMidLabel, orderBuyLabel, orderSellLabel].forEach((n) => { if (n) n.style.display = 'none'; });
2673
+ [edgeLine, edgeLabel, ceilingLine, ceilingLabel, spreadMidLabel, orderBuyLabel, orderSellLabel].forEach((n) => { if (n) n.style.display = 'none'; });
2674
2674
  orderLineDivs.forEach((d) => { d.style.display = 'none'; });
2675
2675
  orderPriceTags.forEach((t) => { t.style.display = 'none'; });
2676
2676
  }
@@ -2678,15 +2678,15 @@ function generateHTML(data, title = 'TradingView Style Research') {
2678
2678
  if (!u || !u.over || !currentCandles.length) return;
2679
2679
  if (!currentOrdersVisible || (!hasOrders && !hasBounds)) { hideOverlayNodes(); return; }
2680
2680
  try { if (getComputedStyle(u.root).position === 'static') u.root.style.position = 'relative'; } catch (e) {}
2681
- if (!reserveLine || reserveLine.parentNode !== u.root) {
2682
- if (reserveLine && reserveLine.parentNode) reserveLine.parentNode.removeChild(reserveLine);
2683
- if (reserveLabel && reserveLabel.parentNode) reserveLabel.parentNode.removeChild(reserveLabel);
2684
- reserveLine = document.createElement('div');
2685
- reserveLine.style.cssText = 'position:absolute;z-index:1;pointer-events:none;height:0;border-top:2px dashed #f97316;opacity:0.7;left:0;right:0;display:none;';
2686
- reserveLabel = document.createElement('div');
2687
- reserveLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 10px Segoe UI, sans-serif;line-height:15px;height:15px;padding:0 5px;border-radius:3px;color:#f97316;background:rgba(30,41,59,0.9);white-space:nowrap;display:none;';
2688
- u.root.appendChild(reserveLine);
2689
- u.root.appendChild(reserveLabel);
2681
+ if (!edgeLine || edgeLine.parentNode !== u.root) {
2682
+ if (edgeLine && edgeLine.parentNode) edgeLine.parentNode.removeChild(edgeLine);
2683
+ if (edgeLabel && edgeLabel.parentNode) edgeLabel.parentNode.removeChild(edgeLabel);
2684
+ edgeLine = document.createElement('div');
2685
+ edgeLine.style.cssText = 'position:absolute;z-index:1;pointer-events:none;height:0;border-top:2px dashed #f97316;opacity:0.7;left:0;right:0;display:none;';
2686
+ edgeLabel = document.createElement('div');
2687
+ edgeLabel.style.cssText = 'position:absolute;z-index:25;pointer-events:none;font:600 10px Segoe UI, sans-serif;line-height:15px;height:15px;padding:0 5px;border-radius:3px;color:#f97316;background:rgba(30,41,59,0.9);white-space:nowrap;display:none;';
2688
+ u.root.appendChild(edgeLine);
2689
+ u.root.appendChild(edgeLabel);
2690
2690
  }
2691
2691
  // Grid bounds span the full DEXBot grid (live + virtual slots
2692
2692
  // in base units), never calculated: bottom = lowest grid buy,
@@ -2699,7 +2699,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
2699
2699
  const gridLow = Number.isFinite(rawLow) && rawLow > 0 ? rawLow : null;
2700
2700
  const gridHigh = Number.isFinite(rawHigh) && rawHigh > 0 ? rawHigh : null;
2701
2701
  const inversePairs = normalizePairMode(currentPairMode) === 'inverse';
2702
- const reservePrice = inversePairs
2702
+ const edgePrice = inversePairs
2703
2703
  ? (gridHigh != null ? 1 / gridHigh : null)
2704
2704
  : gridLow;
2705
2705
  const ceilingPrice = inversePairs
@@ -2708,20 +2708,20 @@ function generateHTML(data, title = 'TradingView Style Research') {
2708
2708
  const ys = u.scales.y || {};
2709
2709
  const rootRect = u.root.getBoundingClientRect();
2710
2710
  const overRect = u.over.getBoundingClientRect();
2711
- const y = reservePrice != null ? yForPriceCached(ys, overRect, rootRect, reservePrice) : null;
2711
+ const y = edgePrice != null ? yForPriceCached(ys, overRect, rootRect, edgePrice) : null;
2712
2712
  if (y == null) {
2713
- reserveLine.style.display = 'none';
2714
- reserveLabel.style.display = 'none';
2713
+ edgeLine.style.display = 'none';
2714
+ edgeLabel.style.display = 'none';
2715
2715
  } else {
2716
- reserveLine.style.display = 'block';
2717
- reserveLine.style.top = y + 'px';
2716
+ edgeLine.style.display = 'block';
2717
+ edgeLine.style.top = y + 'px';
2718
2718
  const lastClose = currentCandles[currentCandles.length - 1].close;
2719
- const dipRaw = Number.isFinite(lastClose) && lastClose > 0 ? (lastClose - reservePrice) / lastClose * 100 : NaN;
2719
+ const dipRaw = Number.isFinite(lastClose) && lastClose > 0 ? (lastClose - edgePrice) / lastClose * 100 : NaN;
2720
2720
  const dipTxt = Number.isFinite(dipRaw) ? (dipRaw >= 0 ? '-' : '+') + Math.abs(Math.round(dipRaw)) + '%' : '-';
2721
- reserveLabel.style.display = 'block';
2722
- reserveLabel.textContent = 'reserve ' + fmtPriceLabel(reservePrice) + ' (' + dipTxt + ')';
2723
- reserveLabel.style.left = '8px';
2724
- reserveLabel.style.top = (y - 16) + 'px';
2721
+ edgeLabel.style.display = 'block';
2722
+ edgeLabel.textContent = 'reserve ' + fmtPriceLabel(edgePrice) + ' (' + dipTxt + ')';
2723
+ edgeLabel.style.left = '8px';
2724
+ edgeLabel.style.top = (y - 16) + 'px';
2725
2725
  }
2726
2726
  if (!ceilingLine || ceilingLine.parentNode !== u.root) {
2727
2727
  if (ceilingLine && ceilingLine.parentNode) ceilingLine.parentNode.removeChild(ceilingLine);
@@ -2878,8 +2878,8 @@ function generateHTML(data, title = 'TradingView Style Research') {
2878
2878
  }
2879
2879
  }
2880
2880
  function resetOverlayNodes() {
2881
- reserveLine = null;
2882
- reserveLabel = null;
2881
+ edgeLine = null;
2882
+ edgeLabel = null;
2883
2883
  ceilingLine = null;
2884
2884
  ceilingLabel = null;
2885
2885
  spreadMidLabel = null;
@@ -64,8 +64,8 @@
64
64
  * "targetSpreadPercent": 2,
65
65
  * "weightDistribution": { "sell": 1, "buy": 1 },
66
66
  * "botFunds": { "sell": "100%", "buy": "100%" },
67
- * "activeOrders": { "sell": 20, "buy": 20 },
68
- * "reserveOrders": { "buy": 0, "sell": 0 }, // Edge reserves: extra live orders (buy: floor, sell: ceiling)
67
+ * "coreOrders": { "sell": 20, "buy": 20 },
68
+ * "edgeOrders": { "buy": 0, "sell": 0 }, // Edge orders: extra live orders (buy: floor, sell: ceiling)
69
69
  * "poolRef": null, // Optional pinned pool ID for startPrice "pool"
70
70
  * "debtPolicy": { ... }, // MPA/credit lending policy — docs/MPA_CREDIT_USAGE.md
71
71
  * "min_BTS_value": 0, // Minimum BTS value threshold for operations
@@ -157,6 +157,7 @@ declare function loadGeneralSettings(): {
157
157
  FILL_TOTALS_RETRY_MAX_MS: number;
158
158
  SPREAD_STALE_WARN_MS: number;
159
159
  SPREAD_STALE_ESCALATE_MS: number;
160
+ SPREAD_CORRECTION_SYNC_FRESH_MS: number;
160
161
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
161
162
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
162
163
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
@@ -379,11 +380,11 @@ declare function loadGeneralSettings(): {
379
380
  sell: string;
380
381
  buy: string;
381
382
  };
382
- activeOrders: {
383
+ coreOrders: {
383
384
  sell: number;
384
385
  buy: number;
385
386
  };
386
- reserveOrders: {
387
+ edgeOrders: {
387
388
  buy: number;
388
389
  sell: number;
389
390
  };
@@ -682,7 +683,7 @@ declare function isPoolRefClearInput(value: unknown): boolean;
682
683
  interface BotDraft extends UnknownRecord {
683
684
  accountId?: string;
684
685
  active?: boolean;
685
- activeOrders: {
686
+ coreOrders: {
686
687
  sell?: number;
687
688
  buy?: number;
688
689
  };
@@ -700,7 +701,7 @@ interface BotDraft extends UnknownRecord {
700
701
  name?: string;
701
702
  poolRef?: string | null;
702
703
  preferredAccount?: string;
703
- reserveOrders?: {
704
+ edgeOrders?: {
704
705
  sell?: number;
705
706
  buy?: number;
706
707
  };
@@ -64,8 +64,8 @@
64
64
  * "targetSpreadPercent": 2,
65
65
  * "weightDistribution": { "sell": 1, "buy": 1 },
66
66
  * "botFunds": { "sell": "100%", "buy": "100%" },
67
- * "activeOrders": { "sell": 20, "buy": 20 },
68
- * "reserveOrders": { "buy": 0, "sell": 0 }, // Edge reserves: extra live orders (buy: floor, sell: ceiling)
67
+ * "coreOrders": { "sell": 20, "buy": 20 },
68
+ * "edgeOrders": { "buy": 0, "sell": 0 }, // Edge orders: extra live orders (buy: floor, sell: ceiling)
69
69
  * "poolRef": null, // Optional pinned pool ID for startPrice "pool"
70
70
  * "debtPolicy": { ... }, // MPA/credit lending policy — docs/MPA_CREDIT_USAGE.md
71
71
  * "min_BTS_value": 0, // Minimum BTS value threshold for operations
@@ -1274,7 +1274,7 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1274
1274
  console.log(`${COLORS.yellowBold}2) Identity:${COLORS.reset} ${COLORS.orange}Name:${COLORS.reset} ${data.name || '?'}, ${COLORS.orange}Account:${COLORS.reset} ${data.preferredAccount || '?'} | ${COLORS.orange}Active:${COLORS.reset} ${colorBooleanFlag(data.active, true)}, ${COLORS.orange}DryRun:${COLORS.reset} ${colorBooleanFlag(data.dryRun, false)}`);
1275
1275
  console.log(`${COLORS.yellowBold}3) Price:${COLORS.reset} ${COLORS.orange}Range:${COLORS.reset} [${colorPriceRangeValue(data.minPrice)} - ${colorPriceRangeValue(data.maxPrice)}] | ${COLORS.orange}Start:${COLORS.reset} ${colorStartPriceValue(data.startPrice)}, ${COLORS.orange}Pool:${COLORS.reset} ${formatPoolRefLabel(data)} | ${COLORS.orange}GridPrice:${COLORS.reset} ${colorGridPriceValue(data.gridPrice)}`);
1276
1276
  console.log(`${COLORS.yellowBold}4) Grid:${COLORS.reset} ${COLORS.orange}Weights:${COLORS.reset} (S:${data.weightDistribution.sell}, B:${data.weightDistribution.buy}) | ${COLORS.orange}Increment:${COLORS.reset} ${data.incrementPercent}%, ${COLORS.orange}Spread:${COLORS.reset} ${data.targetSpreadPercent}%`);
1277
- console.log(`${COLORS.yellowBold}5) Inventory:${COLORS.reset} ${COLORS.orange}Sell:${COLORS.reset} ${colorPercentageInput(data.botFunds.sell)}, ${COLORS.orange}Buy:${COLORS.reset} ${colorPercentageInput(data.botFunds.buy)} | ${COLORS.orange}MarketOrder:${COLORS.reset} (S:${data.activeOrders.sell}, B:${data.activeOrders.buy}) | ${COLORS.orange}EdgeOrder:${COLORS.reset} (S:${data.reserveOrders?.sell ?? 0}, B:${data.reserveOrders?.buy ?? 0})`);
1277
+ console.log(`${COLORS.yellowBold}5) Inventory:${COLORS.reset} ${COLORS.orange}Sell:${COLORS.reset} ${colorPercentageInput(data.botFunds.sell)}, ${COLORS.orange}Buy:${COLORS.reset} ${colorPercentageInput(data.botFunds.buy)} | ${COLORS.orange}CoreOrder:${COLORS.reset} (S:${data.coreOrders.sell}, B:${data.coreOrders.buy}) | ${COLORS.orange}EdgeOrder:${COLORS.reset} (S:${data.edgeOrders?.sell ?? 0}, B:${data.edgeOrders?.buy ?? 0})`);
1278
1278
  {
1279
1279
  const flags = adapterFlags();
1280
1280
  const inert = !isAmaGridPriceDraft() && (flags.ama || flags.dynamicWeight || flags.asymmetricBounds);
@@ -1418,23 +1418,23 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1418
1418
  const fBuy = await askNumberOrPercentage('botFunds buy amount', data.botFunds.buy);
1419
1419
  if (fBuy === undefined || fBuy === '\x1b')
1420
1420
  break;
1421
- const oSell = await askIntegerInRange('activeOrders sell count', data.activeOrders.sell, 1, 100);
1421
+ const oSell = await askIntegerInRange('coreOrders sell count', data.coreOrders.sell, 1, 100);
1422
1422
  if (typeof oSell !== 'number')
1423
1423
  break;
1424
- const oBuy = await askIntegerInRange('activeOrders buy count', data.activeOrders.buy, 1, 100);
1424
+ const oBuy = await askIntegerInRange('coreOrders buy count', data.coreOrders.buy, 1, 100);
1425
1425
  if (typeof oBuy !== 'number')
1426
1426
  break;
1427
- const rBuy = await askIntegerInRange('reserveOrders buy floor count (0 disables)', data.reserveOrders?.buy ?? 0, 0, 100);
1427
+ const rBuy = await askIntegerInRange('edgeOrders buy floor count (0 disables)', data.edgeOrders?.buy ?? 0, 0, 100);
1428
1428
  if (typeof rBuy !== 'number')
1429
1429
  break;
1430
- const rSell = await askIntegerInRange('reserveOrders sell ceiling count (0 disables)', data.reserveOrders?.sell ?? 0, 0, 100);
1430
+ const rSell = await askIntegerInRange('edgeOrders sell ceiling count (0 disables)', data.edgeOrders?.sell ?? 0, 0, 100);
1431
1431
  if (typeof rSell !== 'number')
1432
1432
  break;
1433
1433
  data.botFunds.sell = fSell;
1434
1434
  data.botFunds.buy = fBuy;
1435
- data.activeOrders.sell = oSell;
1436
- data.activeOrders.buy = oBuy;
1437
- data.reserveOrders = { buy: rBuy, sell: rSell };
1435
+ data.coreOrders.sell = oSell;
1436
+ data.coreOrders.buy = oBuy;
1437
+ data.edgeOrders = { buy: rBuy, sell: rSell };
1438
1438
  showMenu = true;
1439
1439
  break;
1440
1440
  case '6': {
@@ -16,10 +16,10 @@
16
16
  * 1. AccountOrders(options) - Class for per-bot order persistence
17
17
  * Constructor options: { botKey, ordersDir?, profilesPath? } (botKey required, throws if missing)
18
18
  * Methods:
19
- * syncMeta(botConfig), storeMasterGrid(orders, btsFeesOwed, boundaryIdx, assets, debugInputs, recentFillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot)
19
+ * syncMeta(botConfig), storeMasterGrid(orders, btsFeesOwed, boundaryIdx, assets, debugInputs, recentFillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot, lastMarketFill)
20
20
  * loadGrid(forceReload), loadRecentFillKeys(forceReload), loadPersistedAssets(forceReload), loadPendingFillCrawls(forceReload)
21
- * loadBoundaryIdx(forceReload), loadBtsBalance(forceReload), loadBtsFeesOwed(forceReload), loadGapEvacStreaks(forceReload), loadGenesis(forceReload), loadLastFillPivot(forceReload)
22
- * clearGrid(), clearPersistedBoundary(), clearPersistedLastFillPivot()
21
+ * loadBoundaryIdx(forceReload), loadBtsBalance(forceReload), loadBtsFeesOwed(forceReload), loadGapEvacStreaks(forceReload), loadGenesis(forceReload), loadLastFillPivot(forceReload), loadLastMarketFill(forceReload)
22
+ * clearGrid(), clearPersistedBoundary(), clearPersistedLastFillPivot(), clearPersistedLastMarketFill(), backupSnapshot(reason)
23
23
  * loadProcessedFills(options), updateProcessedFillsBatch(fills), cleanOldProcessedFills(olderThanMs)
24
24
  * getAssetBalances(forceReload)
25
25
  *
@@ -109,6 +109,12 @@ interface BotData {
109
109
  ts: number;
110
110
  }[];
111
111
  lastFillPivot?: unknown;
112
+ /** Bot-scoped last-market-fill reference (survives grid regeneration). */
113
+ lastMarketFill?: {
114
+ price: number;
115
+ type: string;
116
+ fillsAt: number;
117
+ };
112
118
  }
113
119
  /**
114
120
  * AccountOrders class - manages order grid persistence
@@ -214,7 +220,7 @@ declare class AccountOrders {
214
220
  * @param {Object|null} recentFillKeys - Optional fill key dedup snapshot for crash recovery
215
221
  * @param {Object|null} genesis - Optional frozen genesis (priceLevels etc)
216
222
  */
217
- storeMasterGrid(orders?: unknown[], btsFeesOwed?: number | null, boundaryIdx?: number | null, assets?: Record<string, unknown> | null, debugInputs?: unknown, recentFillKeys?: Record<string, unknown> | null, genesis?: unknown, gapEvacStreaks?: unknown, pendingFillCrawls?: unknown, lastFillPivot?: unknown): Promise<void>;
223
+ storeMasterGrid(orders?: unknown[], btsFeesOwed?: number | null, boundaryIdx?: number | null, assets?: Record<string, unknown> | null, debugInputs?: unknown, recentFillKeys?: Record<string, unknown> | null, genesis?: unknown, gapEvacStreaks?: unknown, pendingFillCrawls?: unknown, lastFillPivot?: unknown, lastMarketFill?: unknown): Promise<void>;
218
224
  /**
219
225
  * Erase a poisoned persisted boundary after GRID-LOAD rejects it with no
220
226
  * safe re-derivation. storeMasterGrid deliberately never writes a null
@@ -279,6 +285,32 @@ declare class AccountOrders {
279
285
  fillsAt: number;
280
286
  genesisHash: string;
281
287
  } | null;
288
+ /**
289
+ * Load the persisted bot-scoped last-market-fill reference.
290
+ * @param {boolean} forceReload - If true, reload from disk
291
+ * @returns {Object|null} {price, type, fillsAt} or null when absent/invalid
292
+ */
293
+ loadLastMarketFill(forceReload?: boolean): {
294
+ price: number;
295
+ type: string;
296
+ fillsAt: number;
297
+ } | null;
298
+ /**
299
+ * Erase a persisted last-market-fill row that restoreLastMarketFill
300
+ * rejected (TTL expiry / malformed). Mirrors clearPersistedLastFillPivot:
301
+ * without an explicit erase a dead row would re-arm the same rejection on
302
+ * every restart. Load-time only.
303
+ */
304
+ clearPersistedLastMarketFill(): Promise<void>;
305
+ /**
306
+ * Copy the on-disk snapshot to a timestamped sibling file before a
307
+ * destructive operation (snapshot rejection / regeneration). The reason tag
308
+ * is sanitized into the suffix: `<profile>.rejected-drift-<ts>`. Owns the
309
+ * path/storage knowledge so callers never reach through to the filesystem.
310
+ * @param {string} [reason='backup'] - Reason tag for the filename
311
+ * @returns {Promise<string|null>} Backup path, or null when absent/failed
312
+ */
313
+ backupSnapshot(reason?: string): Promise<string | null>;
282
314
  /**
283
315
  * Load persisted pending fill crawls for this bot.
284
316
  * @param {boolean} forceReload - If true, reload from disk