dexbot 1.7.0 → 1.7.2
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 +70 -0
- package/README.md +3 -3
- package/analysis/README.md +33 -13
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.js +5 -6
- package/dist/analysis/analyze_liquidity.js +15 -4
- package/dist/analysis/bot_key_utils.d.ts +44 -1
- package/dist/analysis/bot_key_utils.js +76 -7
- package/dist/analysis/fills_cache.js +2 -1
- package/dist/analysis/grid_correction_check.d.ts +1 -19
- package/dist/analysis/grid_correction_check.js +12 -30
- package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
- package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
- package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
- package/dist/analysis/liquidity/liquidity_view.js +11 -0
- package/dist/analysis/resolve_bot_accounts.js +7 -6
- package/dist/analysis/trade_profitability.js +2 -1
- package/dist/credential-daemon.js +13 -2
- package/dist/dexbot.js +4 -4
- package/dist/modules/account_bots.d.ts +12 -1
- package/dist/modules/account_bots.js +7 -5
- package/dist/modules/account_orders.d.ts +12 -0
- package/dist/modules/account_orders.js +30 -0
- package/dist/modules/bitshares-native/transport.js +24 -6
- package/dist/modules/bitshares_client.d.ts +24 -6
- package/dist/modules/bitshares_client.js +44 -7
- package/dist/modules/bot_settings.d.ts +2 -0
- package/dist/modules/constants.d.ts +28 -3
- package/dist/modules/constants.js +79 -10
- package/dist/modules/dexbot_class.d.ts +23 -6
- package/dist/modules/dexbot_class.js +44 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +128 -8
- package/dist/modules/dexbot_cow_runtime.js +688 -188
- package/dist/modules/dexbot_fill_runtime.js +124 -35
- package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
- package/dist/modules/dexbot_maintenance_runtime.js +259 -79
- package/dist/modules/dexbot_startup_runtime.js +32 -20
- package/dist/modules/dexbot_state_recovery.d.ts +33 -1
- package/dist/modules/dexbot_state_recovery.js +167 -5
- package/dist/modules/node_connect_policy.d.ts +8 -1
- package/dist/modules/node_connect_policy.js +18 -2
- package/dist/modules/node_flap_score.d.ts +87 -0
- package/dist/modules/node_flap_score.js +124 -0
- package/dist/modules/node_health_cache.d.ts +40 -3
- package/dist/modules/node_health_cache.js +66 -20
- package/dist/modules/node_manager.d.ts +101 -19
- package/dist/modules/node_manager.js +255 -65
- package/dist/modules/order/accounting.d.ts +9 -4
- package/dist/modules/order/accounting.js +131 -19
- package/dist/modules/order/async_lock.d.ts +7 -1
- package/dist/modules/order/async_lock.js +7 -1
- package/dist/modules/order/export.js +25 -18
- package/dist/modules/order/fill_ledger.d.ts +99 -0
- package/dist/modules/order/fill_ledger.js +103 -0
- package/dist/modules/order/format.d.ts +24 -10
- package/dist/modules/order/format.js +30 -10
- package/dist/modules/order/grid.d.ts +75 -18
- package/dist/modules/order/grid.js +289 -72
- package/dist/modules/order/grid_reconcile.d.ts +5 -1
- package/dist/modules/order/grid_reconcile.js +333 -210
- package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
- package/dist/modules/order/grid_reconcile_internal.js +223 -91
- package/dist/modules/order/index.d.ts +18 -5
- package/dist/modules/order/index.js +5 -5
- package/dist/modules/order/lifecycle.d.ts +353 -0
- package/dist/modules/order/lifecycle.js +1109 -0
- package/dist/modules/order/manager.d.ts +277 -20
- package/dist/modules/order/manager.js +680 -64
- package/dist/modules/order/placement_lock.d.ts +102 -0
- package/dist/modules/order/placement_lock.js +222 -0
- package/dist/modules/order/strategy.js +13 -1
- package/dist/modules/order/sync_engine.d.ts +74 -114
- package/dist/modules/order/sync_engine.js +254 -198
- package/dist/modules/order/utils/math.d.ts +29 -4
- package/dist/modules/order/utils/math.js +61 -4
- package/dist/modules/order/utils/order.d.ts +106 -37
- package/dist/modules/order/utils/order.js +256 -81
- package/dist/modules/order/utils/system.d.ts +99 -6
- package/dist/modules/order/utils/system.js +249 -35
- package/dist/modules/order/utils/validate.d.ts +7 -1
- package/dist/modules/order/utils/validate.js +48 -2
- package/dist/modules/outcome.d.ts +54 -0
- package/dist/modules/outcome.js +51 -0
- package/dist/modules/settings_merge.d.ts +4 -0
- package/dist/modules/settings_merge.js +9 -0
- package/dist/modules/timing_policy.d.ts +82 -0
- package/dist/modules/timing_policy.js +244 -0
- package/dist/modules/types.d.ts +149 -22
- package/dist/scripts/analyze-credit.js +54 -17
- package/dist/scripts/analyze-orders.d.ts +4 -2
- package/dist/scripts/analyze-orders.js +113 -34
- package/dist/scripts/chart_targets.js +11 -15
- package/dist/scripts/test-credit-renewal.js +12 -5
- package/docs/COW_INVARIANTS.md +71 -8
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +1 -1
- package/docs/GRID_RECONCILE.md +18 -13
- package/docs/LOGGING.md +25 -1
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +183 -26
- package/docs/README.md +23 -2
- package/docs/WORKFLOW.md +9 -3
- package/docs/architecture.md +68 -13
- package/docs/developer_guide.md +25 -8
- package/modules/README.md +6 -0
- package/package.json +3 -3
- package/scripts/README.md +16 -0
- package/scripts/pdev.sh +14 -1
- package/scripts/pmain.sh +23 -8
- package/scripts/ptest.sh +7 -0
- package/tests/README.md +30 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,76 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.7.2] - 2026-11-04 - One Fill Contract with Fail-Closed Grid Blockers, Single Fill Identity, Broadcast-Region Leak Repair, Fill-Anchored Rebuild Boundary, Spread Rotation Into Orphaned Rails
|
|
6
|
+
|
|
7
|
+
### 2026-11-04
|
|
8
|
+
|
|
9
|
+
- **Feat(order)**: give the fill pipeline one written contract and make its blocking decision fail-closed — the fill path's failures were not missing safeguards but one question answered in several places, so a "wait, then guess" was added wherever the answers disagreed. `docs/FILL_PIPELINE.md` now names the six stages (ingest, ledger, pivot, plan, lease, commit/observe), the four fill states, one owner per question and `INV-FILL-001..007`, with a ratchet test over the ten `_processFillsWithBatching` call sites, the two pivot writers, the three boundary-budget files and the nine dedupe references. `hasUnsettledFills()` peeked four raw fields and returned `{unsettled:false}` on ANY throw — a fail-OPEN answer in a fail-closed system, which is how a grid was updated from a stale master; `resolveGridUpdateBlockers()` now returns eight closed codes and `readFillPipelineState()` is the single field reader (reporting `ok:false`, i.e. unknown-blocker, instead of "settled"), so the prose reason and the codes cannot disagree. Broadcast liveness composes through `getLivePendingBroadcasts` (new read-only `gc:false` mode, so a predicate cannot GC the pending set), the region through `isPlacementActive`, the rebuild through the manager flag; only `unknown-blocker` escalates, after `GRID_BLOCKED_ESCALATE_CYCLES` consecutive attempts (a cycle counter, not a timing window). Behavioral change: the targeted-drift gate now defers on ANY blocker, not only the fill codes — it is a chain-mutating reconcile and the old condition could escalate on an unreadable probe and still reconcile in the same tick. Errors now surface as a stalled-but-bounded grid update rather than a grid built from stale state.
|
|
10
|
+
|
|
11
|
+
- **Feat(order)**: one fill identity — `modules/order/fill_ledger.ts` owns `fillKeyOf` (`buildFillKey` stays as an alias) and `resolveTradedSide`, and `isFillBooked` exposes the persisted store's membership without claiming it (booking still belongs to the store). It is wired into the three former copies of the pays-asset map (`_computeFillContext`, `attributeUnmatchedFillToGrid`, the queued pivot refresh), with the SPREAD price fallback left with the caller that owns the ladder. Docs: `INV-RECON-006` now records the chain-observed typeMismatch exemption, `INV-SYNC-008` records that the pays mapping has one implementation and that `slot.type` is the ACCOUNTING side, not rail identity.
|
|
12
|
+
|
|
13
|
+
- **Fix(order)**: claim the fill key at credit time and drop the duplicate amount channel — `processFillAccounting` wrote the store tracker only AFTER a successful persist flush, so in the window between "key queued" and "flush done" a second event with the same key passed the duplicate check (the only protection was the bot-level 5 s claim lease, absent in a bare manager); "credited" and "tracked" could disagree, which is the family that produced the double-released size and the phantom residual. The key is now claimed in the store tracker BEFORE `_applyBalanceAdjustments` and before the pass-1 marker is consumed, and released on every failure path, so "credited => tracked" and "not credited => no claim" hold; `_applyBalanceAdjustments` is ALL-OR-NOTHING (an applied prefix is reversed before the error propagates) so the released claim's retry cannot apply that prefix twice; `_isNewFillKey` asks the store first, so a booked key is refused at ingest even after its lease expired instead of after a `FILL DETECTED` log and queue work. The boolean half of the applied amount (`alreadyAppliedChainSize` / `__chainSizeAlreadyApplied` and its dead consume wrapper) is REMOVED rather than asserted: the aggregated path read it off the LAST group entry only, which is exactly the phantom-residual bug — one channel remains, the amount. `FILL_DEDUPE_WINDOW_MS` stays, re-documented as a CLAIM LEASE: claims restored from the crash snapshot are the one case where nobody knows whether the credit happened, and blocking them forever loses a fill. `docs/FILL_PIPELINE_PLAN.md` is folded into `docs/FILL_PIPELINE.md` and removed. Risk: a failure inside the credit now releases the claim and the fill is retried; the all-or-nothing rollback is what makes that retry safe. No order sizing, boundary or strategy behaviour changed.
|
|
14
|
+
|
|
15
|
+
- **Fix(order)**: make the fill claim a real single winner and delete the second grace-stamp writer — the pre-credit duplicate check ran before `persist()` awaited, so two concurrent `processFillAccounting` calls could both pass it and both credit (reproduced: 998 base / 100005 quote for one fill); the claim is now a synchronous check-and-set with no await in between, and the loser returns duplicate without discarding the queued write (keyed by fill key, it belongs to the winner) and without being counted as a booking. The claim, the duplicate gate and rollback now use ONE map (the store tracker when the store exists, the manager tracker otherwise); in a wired bot they are the same map, but a split fixture would otherwise claim a key the ingest check cannot see. `recordOrderPlacement` is deleted: it had no production caller, and its "writes through the same facade" comment was false — it wrote `_placedAt` directly, which `isFreshlyPlacedOrder` ignores whenever `getLifecycle` exists. The offline exporter now derives BUY/SELL through the ledger's `resolveTradedSide` instead of its own copy of the pays-asset mapping, keeping its stricter "both sides must be this pair" guard. Also corrects retention wording: a booked key is refused while retained regardless of age; `FILL_RECORD_RETENTION_MS` bounds retention, it is not an expiry that re-allows a credit.
|
|
16
|
+
|
|
17
|
+
- **Fix(order)**: release leaked broadcast regions and never park a chain-observed wrong-side cancel — the COW batch executor called `startBroadcasting()` before building ops, but only the inner broadcast `try/finally` released the refcount, so every early return in between (all CREATEs skipped by the last-fill/size guards, fund validation, stale-plan re-plan, single-flight/placement aborts) leaked the region and froze the fill consumer until the 120 s stale-flag watchdog; the delayed backlog was then replayed chunk by chunk against a stale boundary and the bot re-placed sells below levels it had already sold. The region is now tracked per frame and released from the inner finally, the catch and the outer finally (idempotently, so a second raw `stopBroadcasting()` cannot underflow another holder) and released before the best-effort cleanup, and a chain-observed typeMismatch is exempt from the 15-minute fresh-placement grace because a wrong-side order is known-wrong — letting it rest misclassifies its next fill (phantom zero-size fill, dust cancel, re-buy at the fill level); regular surplus cancels keep the grace. A `typeMismatch` the pre-batch drain did not resolve (deferred by an active region or failed) is no longer parked either, while a plan-shaped `reason='type-mismatch'` action still waits, because it only proves `master != target` — the stale-target lag the grace exists for.
|
|
18
|
+
|
|
19
|
+
- **Fix(order)**: derive the fill side from the paid asset — a slot can be retyped (BUY↔SELL) before its resting chain order is corrected, and `_computeFillContext()` trusted `matchedGridOrder.type`, so a real SELL fill on a BUY-typed slot converted the paid base amount with quote precision: `filledAmount` became 0, the slot was treated as partially filled and the bot re-bought at the fill level (2026-11-04 incident). The side is now resolved from the fill's paid asset for every slot type (pays quote = BUY, pays base = SELL), which also selects the correct size asset (BUY=quote, SELL=base) so `filledAmount`/precision stay dimensionally consistent with the order; SPREAD without a usable pays asset keeps the price-vs-`startPrice` fallback, non-SPREAD without one keeps the slot type, and the same undefined/undefined identity collision is guarded in the unmatched-fill attribution and the queued pivot refresh. `fillProcessing.COALESCE_BACKLOG_REPLAY` is rolled out for the configured bots (profile data, ignored by git); the code default stays OFF. Risk: a slot whose fill carries no pays asset id keeps the previous side inference.
|
|
20
|
+
|
|
21
|
+
- **Fix(order)**: repair a wrong-side slot on rail geometry, not on the stored label — a partial fill stores the traded side into the slot so `size` stays dimensionally consistent for accounting/`recalculateFunds`, which made a queued typeMismatch entry look "repaired" and dropped the residual cancel, leaving the order on the wrong rail. The correction validators now treat a level as repaired only when the stored type AND its rail geometry (index vs boundary, including the gap band) agree with the chain side; unknown geometry keeps the old stored-type check so a rail is never invented. Covered by the cancel-guard, geometry and fill-side edge-case suites (`test_fresh_placement_cancel_grace_paths`, `test_correction_queue_staleness`, `test_live_geometry_provenance`, `test_sync_fill_history_batch`), each mutation-checked.
|
|
22
|
+
|
|
23
|
+
- **Fix(grid)**: anchor a rebuilt or reloaded boundary to the last fill — a rebuild/reload derived the band from the live market center while the LAST-FILL-GUARD pivot survived; when the center sat ahead of the pivot, the startup picker skipped the top buy levels (at/through the fill), filled the same-side window lower and left the first ask at the old `sellStart`, so the realized spread was two grid steps wider than target with no fill reason for the extra width (a live market-pair bot: boundary 159 after a BUY at new-ladder slot 158, realized 2.12% vs the 1.5% target). The existing fill re-anchor now runs on both the rebuild and the load path (`BUY fill at f => boundary <= f - 1`, `SELL fill at f => boundary >= f - gapSlots`) after the pivot is re-armed/restored and before reconcile/re-type, and `applyRebuildFillAnchor()` re-types the rails atomically for the anchored boundary so the counter SELL at `f + gapSlots` is a rail order and the boundary published to runtime consumers matches the slot roles. `loadGrid` previously changed only a local boundary while the persisted value stayed in the manager — fixed. The free-fund spread correction did not run in the incident because no maintenance tick followed bootstrap; the reconcile now owns the first window.
|
|
24
|
+
|
|
25
|
+
- **Fix(spread)**: rotate into orphaned rail slots when funds are fully reserved — a fill-anchored boundary move can leave the two counter levels as orphaned VIRTUAL rail slots (e.g. the old sell window starts two levels above the new `sellStart`), and the spread correction's funding probe read `availableFund=0` because the virtual tail reserved exactly the whole free balance (the chain-truth budget deliberately treats virtual == chainFree equality as a real constraint). Only the no-new-commitment rotation path could repair that, but it was restricted to boundary-promoted gap slots — so a fully allocated rail stayed wide forever even though the far resting orders could have moved into the window edge without any new funds. The rotation source/destination pairing now covers every unfunded tightening candidate, while boundary derivation stays restricted to genuinely promoted destinations so an in-rail orphan rotation cannot invent a boundary move. Pinned by `PF-031` (SELL orphan rotation with virtual == free), `PF-032` (fund-selected BUY blocked by the last fill falls back to the SELL orphan rotation) and `PF-033` (BUY mirror).
|
|
26
|
+
|
|
27
|
+
- **Fix(order)**: make the grid-blocked escalation counter truly consecutive — `GRID_BLOCKED_ESCALATE_CYCLES` is documented as N *consecutive* unreadable cycles, but `noteGridUpdateBlockers` only cleared the counter on a healthy call, and its only caller (the targeted-drift gate) returns before evaluating the gate when `getTargetedSyncReason()` is null; a counter parked at the limit therefore survived an arbitrarily long trigger-less stretch and the first unreadable cycle afterwards fired a structural resync instead of waiting the full window. The trigger-less early return now clears the counter (guarded on the manager), the read-only/GC asymmetry in `getLivePendingBroadcasts` is documented and pinned (a `gc:false` probe keeps an entry the write path would drop — the intended fail-closed answer), and `_gridUpdateBlockedCycles` is declared on `OrderManager`/`OrderManagerLike` so the single writer/reader pair is typed.
|
|
28
|
+
|
|
29
|
+
- **Test(scripts)**: actually run the live suite and ship the cred stub fixture — `test:live` scoped `RUN_LIVE_BITSHARES_TESTS=1` to `npm run build` only (`VAR=x a && b` exports the variable to `a`, not `b`), so `run-tests.js` never saw it and silently skipped all 14 live files (`skippedLive 14`); the env now sits on the runner command (`skippedLive 0`, the live set really runs). `build:tests` also never copied `tests/helpers/foreign_cred_stub.js`, so `test_unlock_foreign_cred_daemon_live` always failed with `ENOENT`; it is copied with the other plain-JS helpers.
|
|
30
|
+
|
|
31
|
+
- **Docs**: consolidate the fill-pipeline documents and resync drifted module comments — `docs/FILL_PIPELINE.md` is now the single fill document (contract, P0–P2 status by commit, the P3–P5 remainder with gates and stop conditions, the accepted decision register D10–D12, regression canaries, implementation log), `ORDER_LIFECYCLE` records that it shipped in v1.7.1 and that the five legacy structures are facade views, `ORDER_ENGINE_POST_1.0_RETROSPECTIVE` marks the v1.7.1 commits released and adds the post-1.7.1 rows, and the fill-pipeline ratchet pins that the `typeMismatch` validator must keep deriving rail geometry rather than trusting `slot.type` (baseline `bc20d574`). A comment-only sweep of `modules/` fixed 10 orphaned/superseded JSDoc blocks, comments naming symbols that do not exist, descriptions contradicting the code (the sync-engine header still described the pre-genesis PASS 2), six drifted TOC inventories (math 78→80, system 43→52 plus a missing fill-pipeline/last-fill-guard section, order 76→82, grid 34 + 3, accounting 26→27, sync_engine 12→14), 30 JSDoc `import('./types')` references pointing at a non-existent file and a non-existent interface, and `@param` lines still using pre-underscore parameter names; `modules/README.md` gains `outcome.ts`, `timing_policy.ts` and the missing `order/` entries. Full suite: 358/358 files (`npm test`), `npm run test:live` 366 pass (5 diagnostics need a configured account); `typecheck`, `typecheck:analysis`, `check:any`, `verify:browser-bundle` (44/44) and the timing-policy audit clean.
|
|
32
|
+
|
|
33
|
+
## [1.7.1] - 2026-11-04 - One Existence Record per Slot, Placement-Region Hardening, Forced-Retreat Gap Evacuation, Fee-Adjusted Pool Depth, Stability-Ranked Nodes
|
|
34
|
+
|
|
35
|
+
### 2026-11-04
|
|
36
|
+
|
|
37
|
+
- **Feat(order)**: unify chain existence behind one lifecycle registry — "does this order exist on chain, and how sure are we?" was answered from seven structures with seven different clocks (`_pendingBroadcasts`, `createUncertain`, `_committedOrderIds` + its built-at stamp, `_orderIdAssignedAt`, `_placedAt`, `_chainSizeAppliedFills`, `_lastUnmatchedChainOrders`), and four read sites each consulted a different subset, which is why every fix resurfaced in a new path. `modules/order/lifecycle.ts` now owns ONE record per slot (intent → chain id → partial → gone) and the legacy structures become live Map/Set views onto it, projected in through `_applyOrderUpdate`, so no site has to remember which structure to touch. Behaviour that falls out of having one answer: sync pass 1 no longer reads an unparseable chain entry as absent (a live-but-undecodable order used to be virtualized and re-CREATEd on top of itself); an ABANDONED pending CREATE records `unknown` instead of a clean hole (a lost receipt turning into a duplicate order); a filled or virtualized id loses protection; the placement stamp lands on the slot record (300 rotations across 5 slots previously leaked 300 unreachable order-keyed records and reported every order as not-freshly-placed); a create-uncertain slot reads `unknown` without writing; and an unrelated slot mutation cannot downgrade unresolved evidence to `intent`. Risk: a consumer that relied on a narrower guard defers cleanup one cycle instead of virtualizing — the fail-safe direction, bounded by 2x the pending-broadcast TTL. Docs: new `docs/ORDER_LIFECYCLE.md`. Covered by new `tests/test_order_lifecycle.ts` plus `recon_fuzz`.
|
|
38
|
+
|
|
39
|
+
- **Feat(order)**: make broadcast uncertainty a typed three-valued outcome — an unknown batch result was encoded as an ad-hoc `uncertain: true` beside a second ad-hoc flag (`ambiguousRead`), set by hand at four sites, so the two could disagree and nothing forced a consumer to handle "we do not know" at all. `modules/outcome.ts` is now the only place those results are constructed (`unknownCowOutcome(cause)` derives both flags from one cause and refuses to let a caller field override them), and the four COW return sites name their cause explicitly (`ambiguous-read`, `unavailable`, `lost-receipt`). Behavioral impact: the same fields are returned with the same values, but they can no longer be set inconsistently. Covered by new `tests/test_outcome_contract.ts` and the extended `test_uncertain_broadcast`.
|
|
40
|
+
|
|
41
|
+
- **Feat(order)**: classify every timing window and gate its growth — the engine carried 84 timing knobs, a number that grew because every "the state was briefly wrong" bug was fixed by adding a wait, and nothing ever removed one. `modules/timing_policy.ts` classifies every window as `external` (how long the outside world takes), `bound` (a leak/GC cap that cannot produce a wrong decision), `policy` (a deliberate product choice) or `self-healing` (compensates for our own lost state — a REMOVAL TARGET that must name the replacing evidence), with the two timings computed from other timings declared as derived. Current split: 33 external, 19 bound, 26 policy, 6 self-healing. `tests/test_timing_policy.ts` fails on an unclassified window, so the inventory can only shrink by decision, and pins the derived relationships under override. The six removal targets are deliberately not deleted here: each changes live trading behaviour and needs live validation. Docs: new `docs/TIMING_INVENTORY.md`. Risk: none behavioural — no value changed and no window removed; only new failure mode is a build failure when an unexplained window is added.
|
|
42
|
+
|
|
43
|
+
- **Test(order)**: add an interleaving fuzzer for the reconciliation engine — the engine's failure modes are interleavings (a fill that lands before the snapshot that would have matched it, a read that lags a confirmed broadcast, a truncated snapshot that looks exactly like "the account is empty"), which example-based tests cannot enumerate. `tests/recon_fuzz.ts` drives the REAL `SyncEngine` against a deterministic scripted chain with nine adversarial operations (land, vanish, partial fill, full fill, orphan, duplicate-level, un-adoptable stray, lagging read, unparseable read) and asserts eight policy-free invariants after EVERY event: one slot per chain id, one order per (type, price) level, lifecycle agreement, structural soundness, fund sanity, and "every parseable chain order is accounted for — tracked, reported unmatched, or queued for cancel". It deliberately asserts no policy ("clean after exactly N cycles" would encode one grace and reject correct alternatives), shrinks a failing sequence to a seed + step count replayable with `RECON_FUZZ_SEED`/`RECON_FUZZ_STEPS`, and fails on vacuous runs via coverage floors. Verified by mutation: dropping a duplicate-level orphan report shrinks to a five-step reproduction. Deliberately not `test_*.ts`, so `npm test` stays pass/fail.
|
|
44
|
+
|
|
45
|
+
- **Fix(order)**: one writer per life-cycle clock, one guard per absence decision — a review of the new lifecycle/placement arc found every finding to be the same shape: one question answered in more than one place. (1) `_commitWorkingGrid` swaps the master map wholesale and bypassed the write funnel, so a COW-placed order got no `assignedAt`/`placedAt` at all — the 15-minute surplus-cancel grace was inert on the PRIMARY placement path; every committed slot is now projected through `_syncLifecycleFromMutation` first. (2) `_applyOrderUpdate` wrote both stamps a second time on top of the funnel; one writer now. (3) `timingWindowMs()` replaces five copy-pasted `Number(TIMING.X) > 0 ? … : <literal>` fallbacks, and the reconcile reads gap geometry and the `createUncertain` marker through `resolveGapSlots`/`isSlotCreateUncertain` instead of raw fields it could disagree with. (4) sync pass 1 asked a SUBSET of the absence guard while the startup reconcile and the recovery sweep asked `isInFlight()`, so an order whose CREATE receipt was merely lost could be virtualized and re-created — all three sites now ask `isInFlight()` through `readSlotLifecycle`. (5) Evidence is now ranked and monotonic within a phase (a local re-assertion cannot overwrite a `chain-snapshot`, and pass-2 adoption records `adoption` evidence), so `observedAt` means "when the chain last told us" again. (6) `observe`/`markIntent`/`setPending` cleared `pending` but left the fingerprint index, so `pendingSize()`/`getPending()` disagreed with the engine's facade. (7) The unresolved bound was refreshable for free (the funnel re-asserts `unknown` on every mutation); `recordedAt` now advances only on a phase change or chain-backed evidence, `markIntentIfResolved` resolves an expired unknown, `prune` can evict past-bound records, and a synthesized record is no longer stamped fresh on every read. Covered by new sections in `tests/test_order_lifecycle.ts` plus `ageChainIdAssignment()` in the order test helpers.
|
|
46
|
+
|
|
47
|
+
- **Fix(order)**: serialize the placement paths and re-verify their lease before broadcasting — a trigger-file grid rebuild could run while a fill-driven COW rebalance was mid-plan: the rebuild marked the working grid stale, the bounded stale-plan handler re-planned from a master with no chain ids, that re-plan emitted CREATEs at levels the startup reconcile was concurrently re-pricing via UPDATE, and the startup surplus sweep cancelled only what its lagging read could see — 25 duplicate-price orders on chain in a production incident. `modules/order/placement_lock.ts` introduces a token-based exclusive placement region (bounded wait, shutdown force-release, `isPlacementLeaseCurrent()` via a token WeakMap), `manager.withPlacement()` is the single acquire/release contract with `allowDuringRebuild` for a rebuild's own reconcile, the COW body and the reconcile now re-check their own lease immediately before `startBroadcasting`/Phase 2 and abort (`PLACEMENT_LEASE_LOST`) or discard the plan instead of shipping from a region the watchdog already released, a stale plan caused by a structural rebuild is aborted instead of re-planned create-only (dropping its pending-broadcast entries), the startup surplus sweep skips on a lagging read or live pending broadcasts, `_clearStalePlacementRegion()` is the single teardown authority (it refuses while a younger pipeline counter proves progress and clears the region's stale broadcast refcount atomically), and `endStructuralRebuild()` notifies region end so "never wake into a live broadcast region" has one spelling. Cancel-only holders stay exempt (a cancel carries its own id and cannot duplicate a CREATE). Docs: `INV-BROADCAST-005`, INV-MAINT-001 correction, placement-region section in architecture/developer guide, new `[PLACEMENT]` LOGGING rows. Covered by new `tests/test_placement_lock.ts`, `tests/test_structural_rebuild_guard.ts`, `tests/test_startup_dust_policy.ts`, plus COW-GUARD-REPLAN-006 and Regression 9i.
|
|
48
|
+
|
|
49
|
+
- **Fix(order)**: close the follow-up gaps in placement and fill-marker handling — an audit of the placement arc found one-directional watchdog cross-checks, a fill-marker flag that could mask a partial applied amount, a reconcile CREATE guard that only matched slot ids, an unrestored per-batch anchor budget, and one liveness policy duplicated three times. Fill accounting: the legacy `alreadyAppliedChainSize` boolean is a FALLBACK, not a floor (a group where one entry was marked no longer skips the unapplied remainder of its siblings), and the zero-remainder brake runs after residual verification so a clamped-to-zero fill is virtualized while the chain residual it leaves is still cancelled. Planner/guards: `getLivePendingBroadcasts()` is the single pending-broadcast liveness policy (used by the COW guard, crossing candidates, the reconcile surplus sweep, the maintenance sync gate and the reconcile CREATE path, replacing two hand-rolled TTLs and a no-TTL raw-map read), reconcile CREATEs are refused on a pending-broadcast level match as well as a slot-id match, and a stale-plan re-plan hands back the abandoned plan's absolute re-anchor so an abandoned plan cannot consume the batch's one anchor. Placement: the maintenance tick no longer tears placement down and clears the refcount in separate steps, and the nested correction drain verifies its inherited lease instead of the always-true `isPlacementActive()`. Covered by extended fill-transition, placement-lock, price-collision and COW re-plan suites.
|
|
50
|
+
|
|
51
|
+
- **Fix(order)**: make pass-1 fill markers accumulate and persist, and revalidate pending CREATEs on startup — the pass-1 size markers were single-shot, in-memory only, and double-released the trade's drum (`3.6604 → 3.3046 → 2.9488`), because the duplicate was the second size release rather than the trade. Markers now accumulate and partially consume, persist with the grid snapshot, and keep the trade's pays/receives in fill accounting; corrupt-snapshot rejection is gated on a settled pipeline (empty fill queue, no fill batch, no deferred rebalance/owed crawls); pending uncertain CREATEs join the CREATE collision set with a 30-minute TTL; PARTIAL update targets are planned at the booked remainder; dust chain-count subtraction uses the actually queued cancel count. Also: the COW placement lease is released on every pre-broadcast exit (the `try/finally` now starts at claim time), a placement stale-region watchdog exists, placement-backed regions defer fills past the broadcast bound instead of falling through into a live region, and the fill queue wakes on pipeline force-clear. Covered by `tests/test_fill_transition_idempotency.ts` and `tests/test_snapshot_reject_gate.ts`.
|
|
52
|
+
|
|
53
|
+
- **Fix(gap-evac)**: let forced retreats evacuate, then re-plan the committed band — a live market-pair bot lost its fixed spread: a fill inside the band crawled the boundary down and stranded the live orders above it, the plan's evacuation rotations were refused as stale by LAST-FILL-GUARD (re-proven against the PRE-COMMIT geometry where those slots are still rail members), the batch committed the retreat with the stranded orders still live, and plans are fill-driven — so on a quiet market nothing ever re-planned and the 2.0% band sat at 1.21% for hours while every plan reported success. `liveRailsConflictWithGap` now identifies the no-consistent-boundary case (`maxBuy > minSell - gap - 1`) and `forcedRetreatJustifiesEvacuation` is the single decision point for all three stale-stamp sites, refusing to override a stamp whose source/dest ids are unparseable; the unstamped branch still re-proves direction and size live, and every other stale stamp still fails closed (the 2026-10-30 bid-edge non-regression is pinned). A committed-geometry sweep (`scheduleGapEvacRepair`, hooked after a successful commit and on every maintenance tick) detects live orders inside the COMMITTED band, re-derives the streak ledger and schedules a fill-less re-plan, with the cancel-only teeth as fallback only (never in the same tick), rate-limited to one repair per bot per minute, and unknown geometry treated as unknown. Docs: `INV-COW-011`, LOGGING rows. Covered by new `tests/test_gap_evac_spread_collapse.ts`.
|
|
54
|
+
|
|
55
|
+
- **Fix(gap-evac)**: don't let the cancel teeth destroy the rotation that evacuates — the first live run of the committed-geometry sweep repaired the band through the wrong path: the sweep ticked the streak ledger a second time for the same observation (a restored streak of 1 reached the cancel threshold of 3 in one cycle), and the cancel-only teeth queued cancels for the two chain orders the plan was rotating, so the pre-batch correction drain executed them first, the UPDATE batch found its own sources gone, and the grid fell back to a structural resync plus full reload. `updateGapEvacuationStreaks` gains `increment: false` (re-derive: prune resolved ids, report readiness) and the sweep uses it, and `splitEvacuationCancelsSupersededByRotations` holds any cancel-only evacuation whose chain order this batch rotates out of the drain (restoring it afterwards, so it is dropped as stale once the slot no longer owns the order) while unrelated corrections keep draining. Behavioral impact: a stranded-band repair is now one batch of in-place price updates — no cancels, no "target(s) missing on chain" rejection, no reload. Docs: `[COW] Holding N gap-evacuation cancel(s)` line and corrected tick/hold semantics.
|
|
56
|
+
|
|
57
|
+
- **Fix(geometry)**: stop reading unknown gap geometry as gap 0 — an absent gap band classified the slot just above the boundary as a SELL rail member, mis-classifying in-band orphan adoption (sync engine, fill runtime) and booking SPREAD-placeholder size on the wrong side (accounting), i.e. it could hide or double-count exactly the orders GAP-EVAC exists to evacuate. `resolveGapSlots` is now the fallback in all four sites. The same "absent reads as 0" pattern made restore telemetry lie: `loadGrid` called `_restoreBoundary` before publishing `_gapSlots`, and `_logBoundaryDebug` read the raw field with a `0` fallback, so every restart printed `gapSlots=0 sellStart=boundary+1 spreadCount=0` — indistinguishable from a genuinely collapsed band (this is what produced the "bot lost its fixed spread, only one slot is used" report on a healthy 4-slot band). `_gapSlots` is published before the restore gate, the debug line resolves through `resolveGapSlots` and prints `spreadCount=?` until measured (new `_spreadCountKnown`, so a measured EMPTY band still prints 0). Behavioral impact: adoption/accounting are unchanged whenever the gap is set (the normal case); only the unknown fallback and the restore line change.
|
|
58
|
+
|
|
59
|
+
- **Fix(order)**: repair stranded boundaries without re-arming on replays — the boundary could teleport on a replayed fill and then stay stranded: the orphan sweep re-attributed already-booked fills (re-arming the pivot and owed crawls from a stale execution price), the refill hold pinned a fill-driven retreat to the old boundary, and both boundary writers refused a move that reduced — but did not eliminate — in-band orders. Fill attribution now runs only when the processed ledger did not report `duplicate`; the refill hold is scoped to the promotion direction (BUY up / SELL down) and resolves its side from the plan/master grid; the re-anchor and the rail clamp share one rule (accept a move only when it strands strictly fewer placed orders than the committed boundary; equal counts and structural refusals stay closed); and spread promotion steps over a same-side placed band edge (absorbing it as a rail member) instead of stopping there, with depth counting both so reserve/stranding caps still bound the slide. Docs: `COW_INVARIANTS`, `GRID_RECONCILE`, architecture, `LOGGING`.
|
|
60
|
+
|
|
61
|
+
- **Fix(analyze)**: classify grid slots by type in `dexbot order` — the report bucketed BUY/SELL slots with `i <= boundaryIdx` slicing, so a live order stranded inside the spread band was dropped from every bucket: the counts summed to fewer slots than the grid holds and the "real" spread was measured from the geometry edge (2.02% reported against 1.21% on chain, with two live buys hidden inside a 4-slot band), which made a collapsed spread invisible to operators exactly when they needed to see it. Buckets and rail lists are now type-based, matching the runtime's `getGridBestPrices`/`calculateSpreadFromOrders`; the new `gapBand.inBandPlaced` names every live order resting strictly inside the band and the report prints a "Spread band occupied" warning; the band width comes from the snapshot's frozen genesis and then the live config, staying unknown when geometry is unknown. Behavioral impact: the reported spread changes for snapshots carrying in-band live orders — that is the point; clean snapshots report exactly as before.
|
|
62
|
+
|
|
63
|
+
- **Fix(analysis)**: use the live last-fill predicate in the offline checker — `analysis/grid_correction_check.ts` carried its own copy of `isLastFillGuardBlocked` labelled "mirrors `modules/order/utils/system.ts` 1:1", which had already drifted (it still returned the removed `halfInc` band term). The checker now imports the predicate from the runtime module, so the offline verdict is the runtime binding rather than a re-derivation; the direction verdicts are unchanged, and the rule's release in the header and `--help` is corrected from v1.6.16+ to v1.6.17+.
|
|
64
|
+
|
|
65
|
+
- **Fix(node)**: rank nodes by connection stability, not ping alone — a live run showed all 52 abnormal socket closes landing on the three CDN-fronted public endpoints while the endpoints that were never selected dropped none, and the bot spent 46% of its connected time on the flapping ones: selection sorted on raw latency, and live-transport strikes were erased by a successful health probe, so the blacklist threshold was almost unreachable at a 4h probe interval. New `modules/node_flap_score.ts` (pure, browser-safe, time-decayed churn scoring: effective latency = latency + Σ 0.5^(age/halfLife) · perDrop over a capped 24h window) feeds `node_manager`'s ranking, strikes now decay over `FAILURE_STRIKE_DECAY_MS` instead of being wiped (ledger reseeded so count and ledger stay in step), churn is persisted through `node_health_cache` (and removing a node no longer erases a sibling's history), `restartBitsharesConnection` keeps a healthy socket when the active node is already valid (~88 needless reconnects/re-subscribes in 18 days), the connect policy keeps the connected node in the candidate list, the credential daemon no longer evicts it, and failure reports name the node the operation actually ran on instead of `getBestNode()`. `FAILURE_STRIKE_DECAY_MS` and the `FLAP_*` defaults are surfaced as `NODES.healthCheck.{strikeDecayMs,flapHalfLifeMs,flapPenaltyMsPerDrop,flapPenaltyMaxMs}`. Behavioral impact: a flapping node is demoted for up to a day and can finally be blacklisted; a stable node still wins on ping when nothing flaps, and `preferredNode` still overrides ranking.
|
|
66
|
+
|
|
67
|
+
- **Feat(cli)**: accept a chain account as the `<bot>` target for `credit`/`order` — `dexbot credit [<bot>]` matched only a bot name/key, so passing an account name or `1.2.x` id (the grouping chain positions actually use) reported "no credit bot found" although `dexbot pnl` accepts `<bot|account>`. The matching rule set had also been duplicated five ways with subtly different semantics, so it now lives in `analysis/bot_key_utils` as `matchBotEntryTarget` (name/key), `matchBotAccountTarget` (`preferredAccount` name or typed `1.2.x` id, or the `accountId` stamped by `account_resolver.ts`) and `matchBotTargetIn` (every match, tagged `matchedBy`), letting each caller choose the spellings it accepts; an account target selects every bot entry on it. Diagnostics now separate "no such bot/account", "matched only inactive entries" and "no enabled entry has `debtPolicy.lending`", listing matched entries instead of asserting nothing matched. Two more copies folded away: the `1.2.x` regex is `isAccountIdRef()` and `analyze-orders` calls `computeBotKey` instead of its own verbatim copy. `tv`/`dw`/`liquid` stay bot-only (one account can back several bots). Read-only surface; bot runtime untouched. Docs: README cheat sheet, `docs/WORKFLOW.md`, `analysis/README.md`, `scripts/README.md`, help/examples. Covered by new `tests/test_credit_cli_target.ts` and `tests/test_bot_key_utils.ts`.
|
|
68
|
+
|
|
69
|
+
- **Feat(liquidity)**: price the pool curve net of the AMM fee and show both spreads — the depth chart plotted the raw `x*y = k` curve, so the pool's two sides met at the reserve price even though a taker always pays the pool fee: the pool looked like a zero-spread venue and the fee existed only as a badge. The curve is now parameterized by the fee-adjusted effective price (the chain takes the fee off the output side and keeps it), so bid and ask depth stop at `(1-f)·p0` and `p0/(1-f)` — the fee band a taker must cross — while cumulative depth keeps its local slope and still satisfies `x*y = k` for the fee-free reserves; `f = 0` collapses onto the previous curve. The chart shades the order-book spread next to the pool fee band, the readout lists each percentage with its absolute edges and tags the tighter one, and both follow an inverted price. The guide labels moved out of the band into one aligned block drawn at a device-pixel-ratio-correct size (uPlot leaves the 2D context unscaled, so the fixed 11px font rendered at half size on HiDPI). Percentages share one rule through `formatPercentLabel` (2 decimals below 100%, 1 from 100%, none from 1000%, fixed-point so SI suffixes cannot leak into a spread). Display-only: no bot, adapter or order-engine path touched. Covered by `tests/test_liquidity_depth.ts` and `tests/test_format_percent.ts`.
|
|
70
|
+
|
|
71
|
+
- **Fix(scripts)**: abort branch promotion before it moves anything and make `pmain` atomic — the force-push promotion scripts could move a ref before discovering that the remote was unreachable (a live SSH outage left a half-synced `dev`/`main`). A read-only preflight probe now runs before any ref moves: a dead remote, a missing remote or an unset remote aborts with a clear message before `test`/`dev` and `dev`/`main` diverge, and `pmain` mirrors both refs through one atomic push so it can no longer half-sync. The probe honours a skip env for CI and is documented as point-in-time: a flapping auth path can still fail at the push, where the atomic mirror bounds the damage to "neither". Docs: `scripts/README.md`, `docs/WORKFLOW.md`. Verified with `bash -n` on all four scripts and against the live outage (5/6 probes aborted, every ref unchanged).
|
|
72
|
+
|
|
73
|
+
- **Docs**: record the lifecycle and timing invariants and reconcile the retrospective — new `INV-LIFE-001..005` (unknown is never gone; one record per slot; one definition per guard — absence uses `isInFlight`, the committed guard uses `isRecentlyCommitted`, the fresh-id guard uses `isRecentlyAssigned`; unresolved records are never evicted or downgraded; an unparseable chain entry makes absence unknown, not absent) and `INV-TIME-001` (every timing window is classified, and a self-healing window must name the evidence that replaces it) join the stable theory contract, so a change that reintroduces the old ambiguity is a review failure rather than a judgement call. `ORDER_ENGINE_POST_1.0_RETROSPECTIVE` is rescoped from v1.6.14 to v1.7.0 plus the unreleased arc (§9.10 marked released in v1.6.18, new §9.11 on fill identity/the pivot as a row/one existence record/violation-reducing repair, three new bug families in R2, four "what fixed it" entries in R4, lessons 12-14, a dead cited hash corrected), `COW_INVARIANTS` states the real duplicate rule (`chainPriceOnSameLevel`, not `calculatePriceTolerance`) and renumbers/extends the life-cycle invariants, `GRID_PRICE_INVARIANT` moves its review baseline to v1.7.0, and `modules/README.md` lists `order/lifecycle.ts` and `order/placement_lock.ts`. Full suite: 353/353 files (`npm test`, 14 live tests skipped); `typecheck`, `typecheck:analysis`, `check:any` and `verify:browser-bundle` clean.
|
|
74
|
+
|
|
5
75
|
## [1.7.0] - 2026-11-02 - Liquidity Depth Chart & `dexbot liquid`, Asset Distribution Shortcut, Pool-Ref Chart Targets, Case-Insensitive Asset Lookup, Orphan-Fill Attribution & Stale-Grid Re-Buy Discipline
|
|
6
76
|
|
|
7
77
|
### 2026-11-02
|
package/README.md
CHANGED
|
@@ -337,7 +337,7 @@ dexbot reset {all|<bot>} # Regenerate grid
|
|
|
337
337
|
dexbot disable {all|<bot>} # Disable bot in config
|
|
338
338
|
dexbot enable {all|<bot>} # Enable bot in config
|
|
339
339
|
|
|
340
|
-
dexbot order [<bot>]
|
|
340
|
+
dexbot order [<bot|account>] # Grid state: spread, increment, funds (--export → HTML)
|
|
341
341
|
dexbot export <bot> # Trades + settings → CSV/JSON for analysis/
|
|
342
342
|
|
|
343
343
|
dexbot tv <bot|pool|A/B> # TradingView 1h chart with AMA overlay (default: 3 months)
|
|
@@ -345,14 +345,14 @@ dexbot dw <bot|pool|A/B> # Dynamic-weight research chart (same targets/flag
|
|
|
345
345
|
dexbot liquid <bot|pool|A/B> # Liquidity depth: order book + AMM pool (aliases: liq, liqu)
|
|
346
346
|
|
|
347
347
|
dexbot pnl <bot|account> # HTML PnL report (--month N, optional --pair A/B)
|
|
348
|
-
dexbot credit [<bot>]
|
|
348
|
+
dexbot credit [<bot|account>] # Live summed MPA + borrowed-credit positions
|
|
349
349
|
dexbot asset <bts|symbol> # Supply distribution + HTML report (short: dexbot a bts)
|
|
350
350
|
dexbot rich <asset...> # Top holders per asset
|
|
351
351
|
|
|
352
352
|
dexbot update # Update DEXBot2
|
|
353
353
|
dexbot clear # Delete log files in <profiles>/logs
|
|
354
354
|
dexbot default # Reset settings to defaults
|
|
355
|
-
dexbot help # Grouped command reference
|
|
355
|
+
dexbot help # Grouped command reference
|
|
356
356
|
```
|
|
357
357
|
|
|
358
358
|
## 🎯 PM2 Process Management
|
package/analysis/README.md
CHANGED
|
@@ -259,7 +259,7 @@ All amounts use the shared 4-significant-figure formatter (compact `K`/`M`, sign
|
|
|
259
259
|
|
|
260
260
|
### LAST-FILL-GUARD Check (`grid_correction_check.ts`)
|
|
261
261
|
|
|
262
|
-
Validates LAST-FILL-GUARD discipline from the same Kibana fill pipeline as `trade_profitability.ts`. The rule is **direction only** (v1.6.
|
|
262
|
+
Validates LAST-FILL-GUARD discipline from the same Kibana fill pipeline as `trade_profitability.ts`. The rule is **direction only** (v1.6.17+) and comes from the runtime's own `isLastFillGuardBlocked` — the tool imports it instead of re-implementing it, so the offline verdict cannot drift from the live guard. With the previous fill at price `p`, the next order must satisfy `BUY < p` and `SELL > p` (equal price is blocked — a re-place at the just-filled level). There is no increment band: the older `pivot ± i/2` rule blocked a BUY below a SELL fill and a SELL one tick above our cost, i.e. it flagged the tightening placements the engine legitimately makes. A violation is a buy fill at/above its pivot or a sell fill at/below it.
|
|
263
263
|
|
|
264
264
|
**Offline limits:** the tool reconstructs pivots from consecutive fills, so it cannot see the runtime's edge-pinned-fill exclusion (no slot identity per fill) nor the spread-correction bypass — expect rare false positives on wick/insurance fills.
|
|
265
265
|
|
|
@@ -321,28 +321,48 @@ to the book mid, and how far the two diverge.
|
|
|
321
321
|
also swaps bid/ask roles and flips the depth asset to the new quote, so the
|
|
322
322
|
chart stays a valid book view rather than a mirrored picture with the wrong sides
|
|
323
323
|
- **Bids**: order-book bids (`quote` of every bid at price >= p) drawn next to
|
|
324
|
-
the pool's
|
|
324
|
+
the pool's fee-adjusted bid curve, which starts at `(1 - f) * p0` and nets
|
|
325
|
+
`(1 - f) * quoteReserve * (1 - sqrt(p / ((1 - f) * p0)))`
|
|
325
326
|
- **Asks**: order-book asks (`quote` of every ask at price <= p) drawn next to
|
|
326
|
-
the pool's
|
|
327
|
+
the pool's fee-adjusted ask curve, which starts at `p0 / (1 - f)` and is
|
|
328
|
+
`quoteReserve * (sqrt(p * (1 - f) / p0) - 1)`
|
|
329
|
+
- **Spread bands**: the order-book spread (best bid .. best ask, amber) and the
|
|
330
|
+
pool fee band (violet, between the fee-adjusted edges) are both shaded, so the
|
|
331
|
+
two spreads a taker could cross are directly comparable. The overlay lists
|
|
332
|
+
each percentage with its absolute edges and tags the tighter one; clicking the
|
|
333
|
+
x-axis to invert flips both bands with the rest of the view
|
|
327
334
|
|
|
328
335
|
The window is symmetric around the pool price (book mid when there is no pool),
|
|
329
336
|
so the whole `0.5x .. 1.5x` range is visible by default. The chain's
|
|
330
337
|
`get_order_book` side convention is handled by the tool. Pool depth is the exact
|
|
331
|
-
constant-product solution (verified against the `x*y = k` swap invariant)
|
|
332
|
-
AMM taker fee
|
|
333
|
-
in the
|
|
334
|
-
|
|
335
|
-
|
|
338
|
+
constant-product solution (verified against the `x*y = k` swap invariant) and is
|
|
339
|
+
**net of the AMM taker fee** `f` (`taker_fee_percent / 100`): the chain charges
|
|
340
|
+
it on the output side and keeps it in the pool, so a swap's effective price is
|
|
341
|
+
`(1 - f) * p` when selling into the pool and `p / (1 - f)` when buying. The
|
|
342
|
+
curve is parameterized by that effective price, so the two pool curves no
|
|
343
|
+
longer meet at the pool price — they stop at their own edges, `(1 - f) * p0` and
|
|
344
|
+
`p0 / (1 - f)`, and the shaded band between them (`~2f` wide) is the AMM spread
|
|
345
|
+
a taker has to cross. That band is drawn in the chart next to the book spread,
|
|
346
|
+
reported in the readout (`BOOK` / `POOL` rows, with the tighter one tagged) and
|
|
347
|
+
in the header (`BOOK SPREAD`, `FEE … · POOL SPREAD …`), and mirrored in the
|
|
348
|
+
console summary (`pool edge bid/ask`). With `f = 0` the two sides collapse onto
|
|
349
|
+
the pool price and the curves match PoolTool's depth chart exactly. PoolTool's
|
|
350
|
+
`depthchart.py` plots the same fee-free curves with the reciprocal price
|
|
351
|
+
convention (`amount_y * (sqrt(p_pool/p) - 1)` for buys and
|
|
352
|
+
`amount_y * (1 - sqrt(p_pool/p))` for sells).
|
|
336
353
|
|
|
337
354
|
Order-book depth prefers `get_limit_orders` (up to ~300 levels per side) over
|
|
338
355
|
`get_order_book`, which many nodes cap at 50 — otherwise thin far levels are
|
|
339
356
|
silently missing from the curves. If the wider call is unavailable the tool
|
|
340
357
|
falls back to the classic 50-level endpoint.
|
|
341
358
|
|
|
342
|
-
All displayed numbers use DEXBot's
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
359
|
+
All displayed numbers use DEXBot's shared formatters (`modules/order/format.ts`)
|
|
360
|
+
embedded into the generated page so it renders identically offline:
|
|
361
|
+
`formatCurrency` for prices (4 active digits), `formatFundsValue` for amounts,
|
|
362
|
+
and `formatPercentLabel` for every percentage — 2 decimals below 100%
|
|
363
|
+
(`2.27%`, `0.40%`, `18.18%`), 1 from 100% (`100.0%`) and none from 1000%
|
|
364
|
+
(`1235%`), fixed-point so a small percentage never picks up the SI suffixes
|
|
365
|
+
`formatCurrency` produces.
|
|
346
366
|
|
|
347
367
|
```bash
|
|
348
368
|
# Default example pair
|
|
@@ -613,7 +633,7 @@ Details: [bot_fitting/README.md](bot_fitting/README.md)
|
|
|
613
633
|
| `chart_css.ts` | Shared uPlot CSS fragments for generated charts |
|
|
614
634
|
| `chart_ui.ts` | Shared browser-side uPlot helpers (cursor, hover, zoom-reset, sizing) |
|
|
615
635
|
| `math_utils.ts` | Shared math utilities |
|
|
616
|
-
| `bot_key_utils.ts` | Bot-key resolution, candle file lookup, `accountId` persistence (`persistBotAccountId`) |
|
|
636
|
+
| `bot_key_utils.ts` | Bot-key resolution, `<bot|account>` target matching (`matchBotEntryTarget` / `matchBotAccountTarget` / `matchBotTargetIn` — shared by `credit`, `order`, `pnl` and the chart commands), candle file lookup, `accountId` persistence (`persistBotAccountId`) |
|
|
617
637
|
| `account_resolver.ts` | Account resolution for all tools: `preferredAccount` / `--account` → `1.2.x`, stamping the result into `profiles/bots.json` |
|
|
618
638
|
| `chain_pool.ts` | Ephemeral read-only chain client over the built-in node pool (account + asset lookups) |
|
|
619
639
|
| `fills_source.ts` | Shared `fill_order` Kibana fetch/query and the static asset-precision table + on-chain cache |
|
package/claw/package.json
CHANGED
|
@@ -11,9 +11,8 @@
|
|
|
11
11
|
* handling — all of it lives here now.
|
|
12
12
|
*/
|
|
13
13
|
import { getErrorMessage } from '../modules/utils/errors.js';
|
|
14
|
-
import { findBotKeyByAccountRef, loadBotMeta, persistBotAccountId, resolveBotKey } from './bot_key_utils.js';
|
|
14
|
+
import { findBotKeyByAccountRef, isAccountIdRef, loadBotMeta, persistBotAccountId, resolveBotKey } from './bot_key_utils.js';
|
|
15
15
|
import { withReadOnlyClient } from './chain_pool.js';
|
|
16
|
-
const ACCOUNT_ID_RE = /^1\.2\.\d+$/;
|
|
17
16
|
/** Default lookup: ephemeral read-only client over the built-in node pool. */
|
|
18
17
|
async function lookupNameOnChain(name) {
|
|
19
18
|
try {
|
|
@@ -62,7 +61,7 @@ async function resolveBotAccount(botKey, options = {}) {
|
|
|
62
61
|
// An explicit override always wins and is never persisted.
|
|
63
62
|
const override = overrideAccount != null ? String(overrideAccount).trim() : '';
|
|
64
63
|
if (override) {
|
|
65
|
-
if (
|
|
64
|
+
if (isAccountIdRef(override)) {
|
|
66
65
|
return { accountId: override, botKey, botMeta, source: 'override-id', reason: null };
|
|
67
66
|
}
|
|
68
67
|
if (!quiet)
|
|
@@ -79,10 +78,10 @@ async function resolveBotAccount(botKey, options = {}) {
|
|
|
79
78
|
const prefRaw = botMeta.preferredAccount != null ? String(botMeta.preferredAccount).trim() : '';
|
|
80
79
|
if (!prefRaw)
|
|
81
80
|
return { accountId: null, botKey, botMeta, source: null, reason: 'no-preferred-account' };
|
|
82
|
-
const stored =
|
|
81
|
+
const stored = isAccountIdRef(String(botMeta.accountId ?? '')) ? String(botMeta.accountId) : null;
|
|
83
82
|
// A typed 1.2.x preferredAccount is authoritative — the stored accountId is
|
|
84
83
|
// a derived cache and must never override it. Self-heal the cache.
|
|
85
|
-
if (
|
|
84
|
+
if (isAccountIdRef(prefRaw)) {
|
|
86
85
|
if (stored !== prefRaw)
|
|
87
86
|
persistResolvedAccountId(botKey, prefRaw, stored, quiet, botsFile);
|
|
88
87
|
return { accountId: prefRaw, botKey, botMeta, source: 'preferred-id', reason: null };
|
|
@@ -110,7 +109,7 @@ async function resolveBotAccount(botKey, options = {}) {
|
|
|
110
109
|
*/
|
|
111
110
|
async function resolveAccountRef(accountRef, options = {}) {
|
|
112
111
|
const ref = String(accountRef ?? '').trim();
|
|
113
|
-
if (
|
|
112
|
+
if (isAccountIdRef(ref)) {
|
|
114
113
|
return { accountId: ref, botKey: null, botMeta: null, source: 'typed-id', reason: null };
|
|
115
114
|
}
|
|
116
115
|
// Local profile first: a bot whose profile name/key matches the reference
|
|
@@ -23,7 +23,7 @@ import path from 'node:path';
|
|
|
23
23
|
import { pathToFileURL } from 'node:url';
|
|
24
24
|
import { PATHS } from '../modules/paths.js';
|
|
25
25
|
import { getErrorMessage } from '../modules/utils/errors.js';
|
|
26
|
-
import { formatCurrency, formatFundsValue } from '../modules/order/format.js';
|
|
26
|
+
import { formatCurrency, formatFundsValue, formatPercentLabel } from '../modules/order/format.js';
|
|
27
27
|
import { muteChainLogs } from '../modules/utils/chain_logs.js';
|
|
28
28
|
import { withReadOnlyClient } from './chain_pool.js';
|
|
29
29
|
import { computeBookStats, computePoolPrice, resolvePriceWindow, buildDepthSeries, DEFAULT_STEPS, } from './liquidity/liquidity_depth_model.js';
|
|
@@ -55,7 +55,9 @@ function usage() {
|
|
|
55
55
|
' --help show this help',
|
|
56
56
|
'',
|
|
57
57
|
'Conventions: price is quote per base (e.g. QUOTE per BASE); depth is',
|
|
58
|
-
'cumulative quote liquidity (QUOTE) at or better than that price.',
|
|
58
|
+
'cumulative quote liquidity (QUOTE) at or better than that price. Pool',
|
|
59
|
+
'depth is net of the AMM taker fee, so the pool bid/ask curves are',
|
|
60
|
+
'separated by the fee-band spread a taker has to cross.',
|
|
59
61
|
].join('\n');
|
|
60
62
|
}
|
|
61
63
|
function parsePositiveNumber(raw, flag) {
|
|
@@ -234,12 +236,21 @@ function printSummary(snapshot, seriesResult, chartFile, config) {
|
|
|
234
236
|
const priceLabel = `${quote.symbol} per ${base.symbol}`;
|
|
235
237
|
console.log(`[Liquidity] ${base.symbol}/${quote.symbol} (price: ${priceLabel}, depth: ${quote.symbol})`);
|
|
236
238
|
if (pool) {
|
|
237
|
-
|
|
239
|
+
const feeText = pool.feePercent != null ? ` fee=${formatPercentLabel(pool.feePercent)}` : '';
|
|
240
|
+
console.log(` pool ${pool.id ?? 'unknown'} price=${fmtPrice(poolPrice)}${feeText} reserves=${fmtAmount(pool.baseReserve)} ${base.symbol} / ${fmtAmount(pool.quoteReserve)} ${quote.symbol}`);
|
|
241
|
+
// Fee-adjusted edges: the pool curves stop there, so the gap between
|
|
242
|
+
// them is the AMM spread a taker has to cross before the curve starts.
|
|
243
|
+
const bidEdge = seriesResult.poolBidPrice;
|
|
244
|
+
const askEdge = seriesResult.poolAskPrice;
|
|
245
|
+
if (bidEdge != null && askEdge != null) {
|
|
246
|
+
const feeSpread = ((askEdge - bidEdge) / askEdge) * 100;
|
|
247
|
+
console.log(` pool edge bid=${fmtPrice(bidEdge)} ask=${fmtPrice(askEdge)} spread=${formatPercentLabel(feeSpread)} (fee-adjusted, net of taker fee)`);
|
|
248
|
+
}
|
|
238
249
|
}
|
|
239
250
|
else {
|
|
240
251
|
console.log(' pool none');
|
|
241
252
|
}
|
|
242
|
-
console.log(` book ${stats.bidOrders} bids / ${stats.askOrders} asks best bid=${fmtPrice(stats.bestBid)} best ask=${fmtPrice(stats.bestAsk)} mid=${fmtPrice(stats.mid)} spread=${
|
|
253
|
+
console.log(` book ${stats.bidOrders} bids / ${stats.askOrders} asks best bid=${fmtPrice(stats.bestBid)} best ask=${fmtPrice(stats.bestAsk)} mid=${fmtPrice(stats.mid)} spread=${stats.spreadPercent != null ? formatPercentLabel(stats.spreadPercent) : '-'}`);
|
|
243
254
|
console.log(` window ${fmtPrice(window.min)} .. ${fmtPrice(window.max)} (${seriesResult.priceCount} samples, range=${config.range})`);
|
|
244
255
|
// The sampled series is wider than the displayed window so the inverted
|
|
245
256
|
// (1/p) view can stay centered; report depth at the actual window edges.
|
|
@@ -30,6 +30,12 @@ declare function persistBotAccountId(botKey: unknown, accountId: string, filePat
|
|
|
30
30
|
* never silently reuse a stale ID.
|
|
31
31
|
*/
|
|
32
32
|
declare function getStoredBotAccountId(botKey: unknown, expectedRef?: string | null, filePath?: string): string | null;
|
|
33
|
+
/**
|
|
34
|
+
* Chain account id (`1.2.x`) test — the single spelling rule for account ids.
|
|
35
|
+
* Analysis tools used to carry a private copy of this regex (`account_resolver`,
|
|
36
|
+
* `trade_profitability`, `fills_cache`, `resolve_bot_accounts`).
|
|
37
|
+
*/
|
|
38
|
+
declare function isAccountIdRef(ref: unknown): boolean;
|
|
33
39
|
/**
|
|
34
40
|
* Find the bot entry whose preferredAccount matches a raw account reference
|
|
35
41
|
* (case-insensitive). Used by tools that accept a bare account name to locate
|
|
@@ -40,7 +46,44 @@ declare function findBotKeyByAccountRef(ref: unknown, filePath?: string): {
|
|
|
40
46
|
botKey: string;
|
|
41
47
|
meta: BotEntry;
|
|
42
48
|
} | null;
|
|
49
|
+
/**
|
|
50
|
+
* Which spelling of a `<bot|account>` CLI target matched a bot entry.
|
|
51
|
+
* `name`/`key` identify one bot; `account` identifies the chain account and
|
|
52
|
+
* therefore every entry that trades from it.
|
|
53
|
+
*/
|
|
54
|
+
type BotTargetKind = 'name' | 'key' | 'account';
|
|
55
|
+
interface BotTargetMatch {
|
|
56
|
+
botKey: string;
|
|
57
|
+
meta: BotEntry;
|
|
58
|
+
matchedBy: BotTargetKind;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Match one bot entry against a `<bot>` target: display name (the same
|
|
62
|
+
* case/space-insensitive rule `resolveBotKey` uses) or bot key. `botKey` is a
|
|
63
|
+
* parameter because callers that key entries by a stored file name
|
|
64
|
+
* (`analyze-orders` reads `profiles/orders/<botKey>.json`) know the key without
|
|
65
|
+
* an entry, and a key must still match when the config entry is missing.
|
|
66
|
+
*/
|
|
67
|
+
declare function matchBotEntryTarget(entry: BotEntry | null | undefined, target: unknown, botKey?: unknown): BotTargetKind | null;
|
|
68
|
+
/**
|
|
69
|
+
* Does the target name the chain account behind this bot? Covers both stored
|
|
70
|
+
* spellings: `preferredAccount` (name or typed 1.2.x id) and the `accountId`
|
|
71
|
+
* `account_resolver.ts` stamps next to it. Matched case-insensitively — chain
|
|
72
|
+
* account names are lowercase, but operators type them any way they like.
|
|
73
|
+
*/
|
|
74
|
+
declare function matchBotAccountTarget(entry: BotEntry | null | undefined, target: unknown): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Canonical `<bot|account>` target resolution: every entry matching the target
|
|
77
|
+
* as a bot name, a bot key, or the chain account it trades from. This is the
|
|
78
|
+
* one rule set behind `dexbot credit`, `dexbot order` and the chart commands —
|
|
79
|
+
* they previously each carried a slightly different copy (some name-only, some
|
|
80
|
+
* key-only, `credit` a third variant). Each caller picks the spellings it
|
|
81
|
+
* accepts from `matchedBy`: a chart command takes the first `name`/`key` match
|
|
82
|
+
* (an account is ambiguous there), while `credit` reports every match.
|
|
83
|
+
*/
|
|
84
|
+
declare function matchBotTargetIn(entries: Array<BotEntry | null | undefined> | null | undefined, target: unknown): BotTargetMatch[];
|
|
43
85
|
declare function resolveAmaConfig(botKey: unknown): AmaConfig;
|
|
44
86
|
declare function resolveAmaKey(botKey: unknown): string;
|
|
45
|
-
export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
|
|
87
|
+
export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey, isAccountIdRef, matchBotEntryTarget, matchBotAccountTarget, matchBotTargetIn };
|
|
88
|
+
export type { BotTargetKind, BotTargetMatch };
|
|
46
89
|
//# sourceMappingURL=bot_key_utils.d.ts.map
|
|
@@ -7,7 +7,7 @@ const { readJSON, writeJSON } = getStorage();
|
|
|
7
7
|
import { parseJsonWithComments } from '../modules/order/utils/system.js';
|
|
8
8
|
import { MARKET_ADAPTER } from '../modules/constants.js';
|
|
9
9
|
import { loadMarketProfiles } from './tradingview/tradingview_uplot_chart_generator.js';
|
|
10
|
-
import { sanitizeKey } from '../modules/utils/sanitize_key.js';
|
|
10
|
+
import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
|
|
11
11
|
import { isSameAssetSymbol, canonicalizeBotAssetSymbols } from '../modules/utils/asset_symbols.js';
|
|
12
12
|
// Single source of truth for bot keys (named AND unnamed bots) so analysis
|
|
13
13
|
// tools resolve the same files production writes.
|
|
@@ -378,7 +378,7 @@ function patchAccountIdInRaw(filePath, entryIndex, accountId) {
|
|
|
378
378
|
* the file was updated.
|
|
379
379
|
*/
|
|
380
380
|
function persistBotAccountId(botKey, accountId, filePath = PATHS.PROFILES.BOTS_JSON) {
|
|
381
|
-
if (!botKey ||
|
|
381
|
+
if (!botKey || !isAccountIdRef(accountId))
|
|
382
382
|
return false;
|
|
383
383
|
let settings = null;
|
|
384
384
|
try {
|
|
@@ -427,13 +427,21 @@ function getStoredBotAccountId(botKey, expectedRef, filePath = PATHS.PROFILES.BO
|
|
|
427
427
|
if (!meta)
|
|
428
428
|
return null;
|
|
429
429
|
const accountIdRaw = String(meta.accountId ?? '');
|
|
430
|
-
const stored =
|
|
430
|
+
const stored = isAccountIdRef(accountIdRaw) ? accountIdRaw : null;
|
|
431
431
|
if (!stored)
|
|
432
432
|
return null;
|
|
433
433
|
if (expectedRef != null && String(meta.preferredAccount ?? '').toLowerCase() !== String(expectedRef).toLowerCase())
|
|
434
434
|
return null;
|
|
435
435
|
return stored;
|
|
436
436
|
}
|
|
437
|
+
/**
|
|
438
|
+
* Chain account id (`1.2.x`) test — the single spelling rule for account ids.
|
|
439
|
+
* Analysis tools used to carry a private copy of this regex (`account_resolver`,
|
|
440
|
+
* `trade_profitability`, `fills_cache`, `resolve_bot_accounts`).
|
|
441
|
+
*/
|
|
442
|
+
function isAccountIdRef(ref) {
|
|
443
|
+
return /^1\.2\.\d+$/.test(String(ref ?? '').trim());
|
|
444
|
+
}
|
|
437
445
|
/**
|
|
438
446
|
* Find the bot entry whose preferredAccount matches a raw account reference
|
|
439
447
|
* (case-insensitive). Used by tools that accept a bare account name to locate
|
|
@@ -441,7 +449,7 @@ function getStoredBotAccountId(botKey, expectedRef, filePath = PATHS.PROFILES.BO
|
|
|
441
449
|
* or when no bot claims the name.
|
|
442
450
|
*/
|
|
443
451
|
function findBotKeyByAccountRef(ref, filePath = PATHS.PROFILES.BOTS_JSON) {
|
|
444
|
-
if (!ref ||
|
|
452
|
+
if (!ref || isAccountIdRef(ref))
|
|
445
453
|
return null;
|
|
446
454
|
let settings = null;
|
|
447
455
|
try {
|
|
@@ -451,15 +459,76 @@ function findBotKeyByAccountRef(ref, filePath = PATHS.PROFILES.BOTS_JSON) {
|
|
|
451
459
|
return null;
|
|
452
460
|
}
|
|
453
461
|
const entries = Array.isArray(settings?.bots) ? settings.bots : [];
|
|
454
|
-
const want = String(ref).toLowerCase();
|
|
455
462
|
for (let i = 0; i < entries.length; i++) {
|
|
456
463
|
const entry = entries[i];
|
|
457
|
-
if (entry &&
|
|
464
|
+
if (entry && matchBotAccountTarget(entry, ref)) {
|
|
458
465
|
return { botKey: computeBotKey(entry, i), meta: entry };
|
|
459
466
|
}
|
|
460
467
|
}
|
|
461
468
|
return null;
|
|
462
469
|
}
|
|
470
|
+
/** Trimmed target or '' — the positional is user input, so never assume a string. */
|
|
471
|
+
function normalizeBotTarget(target) {
|
|
472
|
+
return typeof target === 'string' ? target.trim() : '';
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Match one bot entry against a `<bot>` target: display name (the same
|
|
476
|
+
* case/space-insensitive rule `resolveBotKey` uses) or bot key. `botKey` is a
|
|
477
|
+
* parameter because callers that key entries by a stored file name
|
|
478
|
+
* (`analyze-orders` reads `profiles/orders/<botKey>.json`) know the key without
|
|
479
|
+
* an entry, and a key must still match when the config entry is missing.
|
|
480
|
+
*/
|
|
481
|
+
function matchBotEntryTarget(entry, target, botKey) {
|
|
482
|
+
const raw = normalizeBotTarget(target);
|
|
483
|
+
if (!raw)
|
|
484
|
+
return null;
|
|
485
|
+
if (entry && isSameBotName(entry.name, raw))
|
|
486
|
+
return 'name';
|
|
487
|
+
const key = String(botKey ?? '').trim();
|
|
488
|
+
if (!key)
|
|
489
|
+
return null;
|
|
490
|
+
return key.toLowerCase() === raw.toLowerCase() || sanitizeKey(key) === sanitizeKey(raw) ? 'key' : null;
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Does the target name the chain account behind this bot? Covers both stored
|
|
494
|
+
* spellings: `preferredAccount` (name or typed 1.2.x id) and the `accountId`
|
|
495
|
+
* `account_resolver.ts` stamps next to it. Matched case-insensitively — chain
|
|
496
|
+
* account names are lowercase, but operators type them any way they like.
|
|
497
|
+
*/
|
|
498
|
+
function matchBotAccountTarget(entry, target) {
|
|
499
|
+
const raw = normalizeBotTarget(target).toLowerCase();
|
|
500
|
+
if (!entry || !raw)
|
|
501
|
+
return false;
|
|
502
|
+
const account = String(entry.preferredAccount ?? '').trim().toLowerCase();
|
|
503
|
+
if (account && account === raw)
|
|
504
|
+
return true;
|
|
505
|
+
const accountId = String(entry.accountId ?? '').trim().toLowerCase();
|
|
506
|
+
return Boolean(accountId) && accountId === raw;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Canonical `<bot|account>` target resolution: every entry matching the target
|
|
510
|
+
* as a bot name, a bot key, or the chain account it trades from. This is the
|
|
511
|
+
* one rule set behind `dexbot credit`, `dexbot order` and the chart commands —
|
|
512
|
+
* they previously each carried a slightly different copy (some name-only, some
|
|
513
|
+
* key-only, `credit` a third variant). Each caller picks the spellings it
|
|
514
|
+
* accepts from `matchedBy`: a chart command takes the first `name`/`key` match
|
|
515
|
+
* (an account is ambiguous there), while `credit` reports every match.
|
|
516
|
+
*/
|
|
517
|
+
function matchBotTargetIn(entries, target) {
|
|
518
|
+
const out = [];
|
|
519
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
520
|
+
for (let index = 0; index < list.length; index++) {
|
|
521
|
+
const entry = list[index];
|
|
522
|
+
if (!entry)
|
|
523
|
+
continue;
|
|
524
|
+
const botKey = computeBotKey(entry, index);
|
|
525
|
+
const matchedBy = matchBotEntryTarget(entry, target, botKey)
|
|
526
|
+
?? (matchBotAccountTarget(entry, target) ? 'account' : null);
|
|
527
|
+
if (matchedBy)
|
|
528
|
+
out.push({ botKey, meta: entry, matchedBy });
|
|
529
|
+
}
|
|
530
|
+
return out;
|
|
531
|
+
}
|
|
463
532
|
function resolveAmaConfig(botKey) {
|
|
464
533
|
const botMeta = loadBotMeta(botKey);
|
|
465
534
|
if (!botMeta)
|
|
@@ -539,5 +608,5 @@ function resolveAmaKey(botKey) {
|
|
|
539
608
|
}
|
|
540
609
|
return 'AMA3';
|
|
541
610
|
}
|
|
542
|
-
export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
|
|
611
|
+
export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey, isAccountIdRef, matchBotEntryTarget, matchBotAccountTarget, matchBotTargetIn };
|
|
543
612
|
//# sourceMappingURL=bot_key_utils.js.map
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
import path from 'node:path';
|
|
27
27
|
import { getStorage } from '../modules/storage/index.js';
|
|
28
28
|
import { PATHS } from '../modules/paths.js';
|
|
29
|
+
import { isAccountIdRef } from './bot_key_utils.js';
|
|
29
30
|
import { writeJsonAtomic } from '../market_adapter/utils/atomic_write.js';
|
|
30
31
|
import { shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, unionQueriedRanges, compactCoverage, mergeSpans, subtractRanges, } from '../market_adapter/utils/month_shards.js';
|
|
31
32
|
import { fetchAllFills } from './fills_source.js';
|
|
@@ -38,7 +39,7 @@ const MAX_COVERAGE_SPANS = 64;
|
|
|
38
39
|
const SHARD_EXT = '.json';
|
|
39
40
|
function accountFileBase(accountId) {
|
|
40
41
|
const s = String(accountId ?? '').trim();
|
|
41
|
-
if (
|
|
42
|
+
if (isAccountIdRef(s))
|
|
42
43
|
return s;
|
|
43
44
|
return s.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'account';
|
|
44
45
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { isLastFillGuardBlocked } from '../modules/order/utils/system.js';
|
|
2
3
|
import { FillRecord } from './fills_source.js';
|
|
3
4
|
interface TradeFill {
|
|
4
5
|
time: string;
|
|
@@ -27,25 +28,6 @@ interface Violation {
|
|
|
27
28
|
/** The pivot itself (BUY must be below / SELL above it). */
|
|
28
29
|
threshold: number;
|
|
29
30
|
}
|
|
30
|
-
/**
|
|
31
|
-
* LAST-FILL-GUARD helper — DIRECTION ONLY relative to the last fill price.
|
|
32
|
-
* BUY blocked if price >= pivot
|
|
33
|
-
* SELL blocked if price <= pivot
|
|
34
|
-
* e.g. pivot 1000 => BUY must be < 1000, SELL must be > 1000
|
|
35
|
-
* Cold (pivot null or lastType null) => disabled. Equal price stays blocked
|
|
36
|
-
* (a re-place at the just-filled level).
|
|
37
|
-
* @param {number} price - Target order price
|
|
38
|
-
* @param {string} type - buy/sell
|
|
39
|
-
* @param {number|null} lastPrice - Most recent fill price
|
|
40
|
-
* @param {string|null} lastType - Most recent fill side (buy/sell)
|
|
41
|
-
* @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
|
|
42
|
-
*/
|
|
43
|
-
declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown): {
|
|
44
|
-
blocked: boolean;
|
|
45
|
-
pivot: number | null;
|
|
46
|
-
halfInc?: number;
|
|
47
|
-
threshold?: number | null;
|
|
48
|
-
};
|
|
49
31
|
declare function classifyFills(fills: FillRecord[]): {
|
|
50
32
|
trades: TradeFill[];
|
|
51
33
|
skipped: number;
|