dexbot 1.6.13 → 1.6.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -4
- package/README.md +2 -2
- package/analysis/README.md +6 -6
- package/analysis/tradingview/README.md +2 -1
- package/claw/README.md +7 -7
- package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
- package/claw/modules/claw_catalog.ts +8 -4
- package/claw/modules/dexbot_profiles.ts +59 -15
- package/claw/modules/types.ts +2 -1
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/claw/skills/margin-trading/SKILL.md +1 -1
- package/claw/skills/margin-trading/references/position-management.md +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
- package/dist/dexbot.js +23 -3
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
- package/dist/modules/account_bots.d.ts +10 -6
- package/dist/modules/account_bots.js +13 -10
- package/dist/modules/account_orders.d.ts +36 -4
- package/dist/modules/account_orders.js +76 -5
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
- package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
- package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
- package/dist/modules/bitshares-native/subscriptions.js +1 -1
- package/dist/modules/bot_defaults.d.ts +29 -4
- package/dist/modules/bot_defaults.js +65 -10
- package/dist/modules/bot_settings.d.ts +4 -0
- package/dist/modules/bot_settings.js +58 -21
- package/dist/modules/config.js +6 -1
- package/dist/modules/constants.d.ts +13 -5
- package/dist/modules/constants.js +36 -5
- package/dist/modules/credit_runtime.d.ts +35 -5
- package/dist/modules/credit_runtime.js +219 -38
- package/dist/modules/dexbot_class.d.ts +23 -0
- package/dist/modules/dexbot_class.js +60 -17
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
- package/dist/modules/dexbot_cow_runtime.js +350 -64
- package/dist/modules/dexbot_credential_client.d.ts +1 -16
- package/dist/modules/dexbot_credential_client.js +1 -1
- package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
- package/dist/modules/dexbot_fill_runtime.js +16 -8
- package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
- package/dist/modules/dexbot_maintenance_runtime.js +104 -70
- package/dist/modules/dexbot_startup_runtime.js +15 -2
- package/dist/modules/dexbot_state_recovery.js +17 -1
- package/dist/modules/key_store.d.ts +0 -5
- package/dist/modules/key_store.js +1 -1
- package/dist/modules/order/accounting.js +11 -11
- package/dist/modules/order/export.js +4 -4
- package/dist/modules/order/format.d.ts +15 -1
- package/dist/modules/order/format.js +19 -1
- package/dist/modules/order/genesis_policy.d.ts +1 -1
- package/dist/modules/order/genesis_policy.js +1 -1
- package/dist/modules/order/grid.d.ts +141 -12
- package/dist/modules/order/grid.js +666 -92
- package/dist/modules/order/grid_reconcile.d.ts +1 -1
- package/dist/modules/order/grid_reconcile.js +9 -8
- package/dist/modules/order/grid_reconcile_internal.js +61 -58
- package/dist/modules/order/index.d.ts +37 -9
- package/dist/modules/order/logger.js +2 -2
- package/dist/modules/order/manager.d.ts +10 -2
- package/dist/modules/order/manager.js +56 -31
- package/dist/modules/order/strategy.d.ts +2 -2
- package/dist/modules/order/strategy.js +51 -21
- package/dist/modules/order/sync_engine.js +22 -9
- package/dist/modules/order/utils/math.d.ts +101 -29
- package/dist/modules/order/utils/math.js +215 -84
- package/dist/modules/order/utils/order.d.ts +58 -58
- package/dist/modules/order/utils/order.js +135 -106
- package/dist/modules/order/utils/system.d.ts +193 -6
- package/dist/modules/order/utils/system.js +394 -31
- package/dist/modules/order/utils/validate.d.ts +1 -1
- package/dist/modules/order/utils/validate.js +71 -59
- package/dist/modules/runtime_settings.d.ts +1 -1
- package/dist/modules/runtime_settings.js +3 -3
- package/dist/modules/types.d.ts +55 -4
- package/dist/scripts/analyze-credit.js +44 -27
- package/dist/scripts/analyze-orders.d.ts +1 -1
- package/dist/scripts/analyze-orders.js +4 -4
- package/dist/scripts/diagnose-pool-history.js +35 -30
- package/dist/scripts/divergence-calc.js +6 -6
- package/dist/scripts/pnl.js +1 -1
- package/dist/scripts/rich_list.d.ts +18 -0
- package/dist/scripts/rich_list.js +461 -0
- package/dist/scripts/run-tests.js +80 -4
- package/dist/scripts/validate_bots.d.ts +1 -1
- package/dist/scripts/validate_bots.js +3 -3
- package/dist/unlock.d.ts +2 -1
- package/dist/unlock.js +11 -5
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
- package/docs/COW_INVARIANTS.md +12 -6
- package/docs/DEXBOT_COMPARISON.md +7 -7
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
- package/docs/GRID_PRICE_INVARIANT.md +3 -3
- package/docs/GRID_RECALCULATION.md +4 -1
- package/docs/GRID_RECONCILE.md +4 -4
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +30 -1
- package/docs/MPA_CREDIT_USAGE.md +11 -6
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
- package/docs/README.md +3 -3
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +62 -8
- package/docs/developer_guide.md +12 -3
- package/market_adapter/README.md +4 -4
- package/modules/README.md +1 -1
- package/package.json +2 -1
- package/scripts/README.md +59 -32
- package/tests/README.md +12 -3
|
@@ -27,10 +27,10 @@ import SyncEngine from './sync_engine.js';
|
|
|
27
27
|
import { calculateCurrentSpread, checkSpreadCondition, checkGridHealth } from './grid.js';
|
|
28
28
|
import * as Format from './format.js';
|
|
29
29
|
import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELINE_TIMING, COW_PERFORMANCE, COW_ACTIONS, GRID_LIMITS } from '../constants.js';
|
|
30
|
-
import { seedBotRuntimeConfig } from '../bot_defaults.js';
|
|
30
|
+
import { seedBotRuntimeConfig, createDefaultBotMetrics } from '../bot_defaults.js';
|
|
31
31
|
import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
|
|
32
32
|
import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
|
|
33
|
-
import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain,
|
|
33
|
+
import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
|
|
34
34
|
import { getErrorMessage, getErrorCode } from '../utils/errors.js';
|
|
35
35
|
const { toFiniteNumber } = Format;
|
|
36
36
|
function stalePlacementDropReason(action, planBoundary) {
|
|
@@ -99,7 +99,7 @@ class COWRebalanceEngine {
|
|
|
99
99
|
this.assets = deps.assets;
|
|
100
100
|
this.config = deps.config;
|
|
101
101
|
}
|
|
102
|
-
async execute({ masterGrid, gridVersion, boundaryIdx, funds, manager = null, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null,
|
|
102
|
+
async execute({ masterGrid, gridVersion, boundaryIdx, funds, manager = null, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, edgeAnchors = null }) {
|
|
103
103
|
const startTime = Date.now();
|
|
104
104
|
const workingGrid = new WorkingGrid(masterGrid, { baseVersion: gridVersion });
|
|
105
105
|
const strategyParams = {
|
|
@@ -219,6 +219,10 @@ class COWRebalanceEngine {
|
|
|
219
219
|
// boundary-hold still judge the plan; no geometry is refused here.
|
|
220
220
|
{
|
|
221
221
|
const railSize = targetGrid?.size ?? 0;
|
|
222
|
+
// Null boundary is DELIBERATELY compared against numeric 0 here:
|
|
223
|
+
// the recovery plan's window is measured from rail start, and an
|
|
224
|
+
// off-rail truncation is exactly the telemetry this warn surfaces
|
|
225
|
+
// (see ANCHOR-007). It never gates the plan.
|
|
222
226
|
const gap = Number(gapSlots) || 0;
|
|
223
227
|
const sellStart = Number(targetBoundary) + gap + 1;
|
|
224
228
|
if (Number.isFinite(sellStart) && railSize > 0 && sellStart >= railSize) {
|
|
@@ -230,13 +234,13 @@ class COWRebalanceEngine {
|
|
|
230
234
|
// stamped UPDATEs above; stale-dropped placements are excluded — a
|
|
231
235
|
// deferred placement justifies nothing). The executor holds the
|
|
232
236
|
// committed boundary when a listed refill is guard-skipped.
|
|
233
|
-
//
|
|
237
|
+
// Edge-ladder CREATEs are excluded (collectRefillSlotIds): edge orders
|
|
234
238
|
// are static edge insurance and their fills never crawl, so a skipped
|
|
235
|
-
//
|
|
239
|
+
// edge order must not pin geometry either.
|
|
236
240
|
const refillSlotIds = collectRefillSlotIds(optimizedActions, {
|
|
237
241
|
config: this.config,
|
|
238
242
|
slots: masterGrid,
|
|
239
|
-
edgeAnchors:
|
|
243
|
+
edgeAnchors: edgeAnchors,
|
|
240
244
|
manager: this
|
|
241
245
|
});
|
|
242
246
|
projectTargetToWorkingGrid(workingGrid, targetGrid, { actions: optimizedActions });
|
|
@@ -430,6 +434,24 @@ class OrderManager {
|
|
|
430
434
|
_lastFilledType;
|
|
431
435
|
_lastFilledAt;
|
|
432
436
|
lastFillPivotSource;
|
|
437
|
+
// Bot-scoped "last market fill" reference. Unlike the genesis-bound
|
|
438
|
+
// LAST-FILL-GUARD pivot (reset with the grid generation), this survives a
|
|
439
|
+
// grid regeneration/rejection and is used ONLY as a market anchor by
|
|
440
|
+
// spread correction (a real fill price must not be traded through).
|
|
441
|
+
// Written by setLastFillPivot on 'fill' provenance; restored at startup
|
|
442
|
+
// from the bot-scoped persisted row under a TTL.
|
|
443
|
+
_lastMarketFillPrice;
|
|
444
|
+
_lastMarketFillType;
|
|
445
|
+
_lastMarketFillAt;
|
|
446
|
+
// Externally-observed live market price (B/A), refreshed from the order
|
|
447
|
+
// book/ticker at a bounded cadence. The spread-correction crossing floor is
|
|
448
|
+
// the NEWER of this read and the fill anchor (an executed trade can be
|
|
449
|
+
// fresher market truth), so the floor tracks current market instead of a
|
|
450
|
+
// possibly days-old fill.
|
|
451
|
+
_liveMarketPrice;
|
|
452
|
+
_liveMarketPriceAt;
|
|
453
|
+
_liveMarketPriceAttemptedAt;
|
|
454
|
+
_lastSyncAt;
|
|
433
455
|
_deferredRebalanceAt;
|
|
434
456
|
_lastHeldPlanSignature;
|
|
435
457
|
_heldPlanSuppressionCount;
|
|
@@ -563,6 +585,13 @@ class OrderManager {
|
|
|
563
585
|
// 'fill' = armed by a real fill (persist-eligible), 'book' = armed by
|
|
564
586
|
// the startup book seed (heuristic, in-memory only), null = unarmed.
|
|
565
587
|
this.lastFillPivotSource = null;
|
|
588
|
+
this._lastMarketFillPrice = null;
|
|
589
|
+
this._lastMarketFillType = null;
|
|
590
|
+
this._lastMarketFillAt = 0;
|
|
591
|
+
this._liveMarketPrice = null;
|
|
592
|
+
this._liveMarketPriceAt = 0;
|
|
593
|
+
this._liveMarketPriceAttemptedAt = 0;
|
|
594
|
+
this._lastSyncAt = 0;
|
|
566
595
|
this._deferredRebalanceAt = 0;
|
|
567
596
|
this._lastHeldPlanSignature = null;
|
|
568
597
|
this._heldPlanSuppressionCount = 0;
|
|
@@ -570,16 +599,12 @@ class OrderManager {
|
|
|
570
599
|
this._lastBoundaryHoldResyncAt = 0;
|
|
571
600
|
this._gapEvacStreaks = new Map();
|
|
572
601
|
this._gapEvacCancelQueued = new Set();
|
|
602
|
+
// Shared counters come from the central factory (createDefaultBotMetrics);
|
|
603
|
+
// the manager-owned runtime counters are added on top.
|
|
573
604
|
this._metrics = {
|
|
574
|
-
|
|
575
|
-
batchesExecuted: 0,
|
|
576
|
-
fillProcessingTimeMs: 0,
|
|
577
|
-
lockContentionEvents: 0,
|
|
578
|
-
maxQueueDepth: 0,
|
|
579
|
-
fundRecalcCount: 0,
|
|
605
|
+
...createDefaultBotMetrics(),
|
|
580
606
|
lockAcquisitions: 0,
|
|
581
607
|
lockContentionSkips: 0,
|
|
582
|
-
gridLockContention: 0,
|
|
583
608
|
spreadRoleConversionBlocked: 0,
|
|
584
609
|
lastSyncDurationMs: 0,
|
|
585
610
|
metricsStartTime: Date.now()
|
|
@@ -1530,9 +1555,9 @@ class OrderManager {
|
|
|
1530
1555
|
* @returns {Array<import('./types').Order>}
|
|
1531
1556
|
*/
|
|
1532
1557
|
getInitialOrdersToActivate() {
|
|
1533
|
-
// Apply
|
|
1534
|
-
const sellCount = Math.max(0, toFiniteNumber(this.config.
|
|
1535
|
-
const buyCount = Math.max(0, toFiniteNumber(this.config.
|
|
1558
|
+
// Apply coreOrders limit from config
|
|
1559
|
+
const sellCount = Math.max(0, toFiniteNumber(this.config.coreOrders?.sell, 1));
|
|
1560
|
+
const buyCount = Math.max(0, toFiniteNumber(this.config.coreOrders?.buy, 1));
|
|
1536
1561
|
// Get minimum sizes for validation
|
|
1537
1562
|
const minOrderSizeFactor = this.config?.gridLimits?.MIN_ORDER_SIZE_FACTOR;
|
|
1538
1563
|
const minSellSize = getMinOrderSize(ORDER_TYPES.SELL, this.assets, minOrderSizeFactor);
|
|
@@ -1543,7 +1568,7 @@ class OrderManager {
|
|
|
1543
1568
|
const minSellSizeInt = floatToBlockchainInt(minSellSize, sellPrecision);
|
|
1544
1569
|
const minBuySizeInt = floatToBlockchainInt(minBuySize, buyPrecision);
|
|
1545
1570
|
// Rail membership by geometry (shared isSlotInRail), mirroring the
|
|
1546
|
-
// reconcile pickers (_pickVirtualSlotsToActivate /
|
|
1571
|
+
// reconcile pickers (_pickVirtualSlotsToActivate / _pickEdgeSlots).
|
|
1547
1572
|
// A freshly generated grid's roles never need this, but the gate keeps
|
|
1548
1573
|
// the startup placement path and the runtime activation path from
|
|
1549
1574
|
// diverging: a slot whose stored type is stale relative to the current
|
|
@@ -1584,21 +1609,21 @@ class OrderManager {
|
|
|
1584
1609
|
}
|
|
1585
1610
|
// Reverse for placement order (lowest first)
|
|
1586
1611
|
validBuys.sort((a, b) => a.price - b.price);
|
|
1587
|
-
//
|
|
1612
|
+
// Edge ladder: edge-pinned orders activate alongside the window
|
|
1588
1613
|
// without consuming its budget. Buys pin at the floor (lowest first),
|
|
1589
1614
|
// sells at the ceiling (highest first). Same min-size gate as the window.
|
|
1590
|
-
const
|
|
1615
|
+
const pickEdgeSlots = (orderType, count, windowed, precision, minSizeInt, ascending) => {
|
|
1591
1616
|
const picked = [];
|
|
1592
1617
|
if (count <= 0)
|
|
1593
1618
|
return picked;
|
|
1594
1619
|
const windowedIds = new Set(windowed.map((o) => o.id));
|
|
1595
1620
|
// Both edges anchor at the live grid's own edge (ladder/rail extreme).
|
|
1596
|
-
const edgeAnchor =
|
|
1621
|
+
const edgeAnchor = resolveLiveEdgeAnchorPrice(this, ascending ? 'buy' : 'sell');
|
|
1597
1622
|
const edge = ascending ? 'floor' : 'ceiling';
|
|
1598
1623
|
const edgeFirst = this.getOrdersByTypeAndState(orderType, ORDER_STATES.VIRTUAL)
|
|
1599
1624
|
.filter((o) => inRailFor(orderType, o))
|
|
1600
1625
|
.filter((o) => parseSlotIndex(o.id) !== null)
|
|
1601
|
-
.sort((a, b) =>
|
|
1626
|
+
.sort((a, b) => compareEdge(a, b, edge, edgeAnchor));
|
|
1602
1627
|
for (const o of edgeFirst) {
|
|
1603
1628
|
if (picked.length >= count)
|
|
1604
1629
|
break;
|
|
@@ -1612,9 +1637,9 @@ class OrderManager {
|
|
|
1612
1637
|
picked.sort((a, b) => ascending ? a.price - b.price : b.price - a.price);
|
|
1613
1638
|
return picked;
|
|
1614
1639
|
};
|
|
1615
|
-
const
|
|
1616
|
-
const
|
|
1617
|
-
return [...validSells, ...
|
|
1640
|
+
const edgeBuys = pickEdgeSlots(ORDER_TYPES.BUY, resolveEdgeCount(this.config, 'buy'), validBuys, buyPrecision, minBuySizeInt, true);
|
|
1641
|
+
const edgeSells = pickEdgeSlots(ORDER_TYPES.SELL, resolveEdgeCount(this.config, 'sell'), validSells, sellPrecision, minSellSizeInt, false);
|
|
1642
|
+
return [...validSells, ...edgeSells, ...validBuys, ...edgeBuys];
|
|
1618
1643
|
}
|
|
1619
1644
|
/**
|
|
1620
1645
|
* Get orders matching the specified type and state.
|
|
@@ -2243,12 +2268,12 @@ class OrderManager {
|
|
|
2243
2268
|
this._gapEvacStreaks = new Map();
|
|
2244
2269
|
if (!(this._gapEvacCancelQueued instanceof Set))
|
|
2245
2270
|
this._gapEvacCancelQueued = new Set();
|
|
2246
|
-
// Live
|
|
2247
|
-
// refill wire so
|
|
2248
|
-
// hole refill (which would let a skipped
|
|
2249
|
-
const
|
|
2250
|
-
buy:
|
|
2251
|
-
sell:
|
|
2271
|
+
// Live edge order anchors, resolved once and shared with the engine's
|
|
2272
|
+
// refill wire so an edge-ladder CREATE can never be classified as a
|
|
2273
|
+
// hole refill (which would let a skipped edge order pin the boundary).
|
|
2274
|
+
const edgeAnchors = {
|
|
2275
|
+
buy: resolveLiveEdgeAnchorPrice(this, 'buy'),
|
|
2276
|
+
sell: resolveLiveEdgeAnchorPrice(this, 'sell')
|
|
2252
2277
|
};
|
|
2253
2278
|
const result = await cowEngine.execute({
|
|
2254
2279
|
masterGrid: this.orders,
|
|
@@ -2260,7 +2285,7 @@ class OrderManager {
|
|
|
2260
2285
|
excludeIds,
|
|
2261
2286
|
gapSlots: this._gapSlots,
|
|
2262
2287
|
evacStreaks: this._gapEvacStreaks,
|
|
2263
|
-
|
|
2288
|
+
edgeAnchors
|
|
2264
2289
|
});
|
|
2265
2290
|
// Phase 3 safety net: act on stuck in-band orders regardless of the
|
|
2266
2291
|
// plan outcome — a plan that aborted for unrelated reasons must not
|
|
@@ -110,7 +110,7 @@ declare class StrategyEngine {
|
|
|
110
110
|
* 1. Derive new boundary index based on fills (boundary crawl)
|
|
111
111
|
* 2. Assign grid roles (BUY/SELL/SPREAD) based on boundary position
|
|
112
112
|
* 3. Calculate budget allocation for each side
|
|
113
|
-
* 4. Apply window discipline (
|
|
113
|
+
* 4. Apply window discipline (coreOrders count limits)
|
|
114
114
|
* 5. Calculate ideal order sizes based on budgets and weights
|
|
115
115
|
* 6. Build target grid map representing desired state
|
|
116
116
|
*
|
|
@@ -129,7 +129,7 @@ declare class StrategyEngine {
|
|
|
129
129
|
* @param {Object} params.config - Bot configuration
|
|
130
130
|
* - targetSpreadPercent {number}: Width of spread zone
|
|
131
131
|
* - incrementPercent {number}: Price step between orders
|
|
132
|
-
* -
|
|
132
|
+
* - coreOrders {Object}: Target active order counts
|
|
133
133
|
* - weightDistribution {Object}: Size weighting for each side
|
|
134
134
|
* @param {Object} params.accountAssets - Asset metadata (precision, IDs)
|
|
135
135
|
* @param {Object} params.funds - Current fund state
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
import { ORDER_TYPES, ORDER_STATES } from '../constants.js';
|
|
50
50
|
import { calculateGapSlots } from './grid.js';
|
|
51
51
|
import { isSlotInRail } from './utils/math.js';
|
|
52
|
-
import { deriveTargetBoundary, getSideBudget, calculateBudgetedSizes,
|
|
52
|
+
import { deriveTargetBoundary, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, resolveEdgeCount, resolveLiveEdgeAnchorPrice, selectEdgeSlots, isShiftEligibleFill } from './utils/order.js';
|
|
53
53
|
import { assignGridRoles } from './utils/order.js';
|
|
54
54
|
import { convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, parseSlotIndex, hasOnChainId, isOrderPlaced } from "./utils/order.js";
|
|
55
55
|
class StrategyEngine {
|
|
@@ -188,7 +188,7 @@ class StrategyEngine {
|
|
|
188
188
|
* 1. Derive new boundary index based on fills (boundary crawl)
|
|
189
189
|
* 2. Assign grid roles (BUY/SELL/SPREAD) based on boundary position
|
|
190
190
|
* 3. Calculate budget allocation for each side
|
|
191
|
-
* 4. Apply window discipline (
|
|
191
|
+
* 4. Apply window discipline (coreOrders count limits)
|
|
192
192
|
* 5. Calculate ideal order sizes based on budgets and weights
|
|
193
193
|
* 6. Build target grid map representing desired state
|
|
194
194
|
*
|
|
@@ -207,7 +207,7 @@ class StrategyEngine {
|
|
|
207
207
|
* @param {Object} params.config - Bot configuration
|
|
208
208
|
* - targetSpreadPercent {number}: Width of spread zone
|
|
209
209
|
* - incrementPercent {number}: Price step between orders
|
|
210
|
-
* -
|
|
210
|
+
* - coreOrders {Object}: Target active order counts
|
|
211
211
|
* - weightDistribution {Object}: Size weighting for each side
|
|
212
212
|
* @param {Object} params.accountAssets - Asset metadata (precision, IDs)
|
|
213
213
|
* @param {Object} params.funds - Current fund state
|
|
@@ -250,16 +250,16 @@ class StrategyEngine {
|
|
|
250
250
|
const boundaryConfig = (!Number.isFinite(Number(config?.startPrice)) && Number.isFinite(genesisStart))
|
|
251
251
|
? { ...config, genesisStartPrice: genesisStart }
|
|
252
252
|
: config;
|
|
253
|
-
// Live
|
|
254
|
-
// grid actually being traded. Resolved once and shared by the
|
|
253
|
+
// Live edge order anchors (single source): the ladder extremes of the
|
|
254
|
+
// grid actually being traded. Resolved once and shared by the edge
|
|
255
255
|
// selection below and the no-crawl classification inside
|
|
256
256
|
// deriveTargetBoundary, so placement and fill classification can never
|
|
257
|
-
// disagree about which slots are
|
|
258
|
-
const
|
|
259
|
-
buy:
|
|
260
|
-
sell:
|
|
257
|
+
// disagree about which slots are edge orders.
|
|
258
|
+
const edgeAnchors = {
|
|
259
|
+
buy: resolveLiveEdgeAnchorPrice(this.manager, 'buy'),
|
|
260
|
+
sell: resolveLiveEdgeAnchorPrice(this.manager, 'sell'),
|
|
261
261
|
};
|
|
262
|
-
const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager._pendingFillCrawls,
|
|
262
|
+
const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager._pendingFillCrawls, edgeAnchors);
|
|
263
263
|
if (crossChunkBudget != null) {
|
|
264
264
|
this.manager._boundaryShiftBudget = remainingBudget;
|
|
265
265
|
}
|
|
@@ -270,20 +270,50 @@ class StrategyEngine {
|
|
|
270
270
|
this.manager.logger.log('[COW] calculateTargetGrid: boundary unrecoverable (no numeric center); skipping rotation plan', 'warn');
|
|
271
271
|
return { targetGrid: new Map(), boundaryIdx: null };
|
|
272
272
|
}
|
|
273
|
+
// P2 observability: a market/fill-derived boundary that jumps more than
|
|
274
|
+
// the active window in ONE plan is the "boundary detached from the
|
|
275
|
+
// market anchor" signal (the ANCHOR-DIVERGENCE condition, which lost its
|
|
276
|
+
// telemetry when the price projection was removed). A normal crawl is
|
|
277
|
+
// budget-bounded to at most half the active window, so this can only fire
|
|
278
|
+
// on an absolute recovery anchor or a geometry fault. Counted and
|
|
279
|
+
// rate-limited; never gates the plan.
|
|
280
|
+
try {
|
|
281
|
+
const activeWindow = Math.max(1, Number(config?.coreOrders?.buy) || 1, Number(config?.coreOrders?.sell) || 1);
|
|
282
|
+
// Null boundary is DELIBERATELY compared against numeric 0 here:
|
|
283
|
+
// the derived boundary is an absolute recovery anchor, and its
|
|
284
|
+
// distance from 0 is exactly the ANCHOR-DIVERGENCE signal this
|
|
285
|
+
// observability counter exists to surface (see P2 test).
|
|
286
|
+
const driftSlots = Math.abs(Number(newBoundaryIdx) - Number(currentBoundaryIdx));
|
|
287
|
+
if (Number.isFinite(driftSlots) && driftSlots > activeWindow) {
|
|
288
|
+
const metrics = this.manager._metrics;
|
|
289
|
+
if (metrics) {
|
|
290
|
+
metrics.boundaryDriftExceedsWindowCount = (metrics.boundaryDriftExceedsWindowCount || 0) + 1;
|
|
291
|
+
}
|
|
292
|
+
const now = Date.now();
|
|
293
|
+
const lastWarn = Number(this.manager._lastBoundaryDriftWarnAt) || 0;
|
|
294
|
+
if (now - lastWarn >= 5 * 60 * 1000) {
|
|
295
|
+
this.manager._lastBoundaryDriftWarnAt = now;
|
|
296
|
+
this.manager.logger.log(`[BOUNDARY-DRIFT] committed boundary ${currentBoundaryIdx} -> planned ${newBoundaryIdx} ` +
|
|
297
|
+
`(drift ${driftSlots} slots) exceeds active window ${activeWindow}; ` +
|
|
298
|
+
`boundary is detached from the market anchor (observability only)`, 'warn');
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
catch { /* observability only */ }
|
|
273
303
|
// 2. Assign Roles (Buy/Sell/Spread)
|
|
274
304
|
const updatedSlots = assignGridRoles(allSlots, newBoundaryIdx, gapSlots, ORDER_TYPES, ORDER_STATES, { assignOnChain: true });
|
|
275
305
|
this.manager.logger.log(`[DEBUG] calculateTargetGrid: boundary=${newBoundaryIdx}, gap=${gapSlots}, allSlots=${updatedSlots.length}`, 'debug');
|
|
276
306
|
updatedSlots.forEach((s) => this.manager.logger.log(` Slot ${s.id}: price=${s.price}, size=${s.size ?? 'n/a'}, type=${s.type}`, 'debug'));
|
|
277
307
|
// 3. Calculate Ideal Sizes (Budgeting)
|
|
278
|
-
const totalTarget =
|
|
308
|
+
const totalTarget = getCoreOrdersTotal(config);
|
|
279
309
|
const budgetBuy = getSideBudget('buy', funds, config, totalTarget);
|
|
280
310
|
const budgetSell = getSideBudget('sell', funds, config, totalTarget);
|
|
281
311
|
// Filter slots into BUY/SELL
|
|
282
312
|
const allBuySlots = updatedSlots.filter((o) => o.type === ORDER_TYPES.BUY);
|
|
283
313
|
const allSellSlots = updatedSlots.filter((o) => o.type === ORDER_TYPES.SELL);
|
|
284
|
-
// Apply Window Discipline (
|
|
285
|
-
const targetCountBuy = Math.max(1, (config.
|
|
286
|
-
const targetCountSell = Math.max(1, (config.
|
|
314
|
+
// Apply Window Discipline (coreOrders count)
|
|
315
|
+
const targetCountBuy = Math.max(1, (config.coreOrders?.buy ?? 1));
|
|
316
|
+
const targetCountSell = Math.max(1, (config.coreOrders?.sell ?? 1));
|
|
287
317
|
// The SPREAD GUARD (assignGridRoles) keeps a live on-chain order typed
|
|
288
318
|
// BUY/SELL even when a boundary crawl moves its slot into the spread
|
|
289
319
|
// band (to avoid the illegal SPREAD+ACTIVE state). Such a stray slot
|
|
@@ -330,17 +360,17 @@ class StrategyEngine {
|
|
|
330
360
|
const fullSellSizes = calculateBudgetedSizes(allSellSortedForSizing, 'sell', budgetSell, config.weightDistribution?.sell, config.incrementPercent, accountAssets);
|
|
331
361
|
const buySizeById = new Map(allBuySortedForSizing.map((slot, i) => [slot.id, fullBuySizes[i] || 0]));
|
|
332
362
|
const sellSizeById = new Map(allSellSortedForSizing.map((slot, i) => [slot.id, fullSellSizes[i] || 0]));
|
|
333
|
-
//
|
|
363
|
+
// Edge ladder: edge-pinned insurance orders stay live alongside the
|
|
334
364
|
// window. Buys pin at the floor (lowest prices), sells at the ceiling
|
|
335
365
|
// (highest prices). Discontiguous by design — the middle stays VIRTUAL.
|
|
336
|
-
// Sizes come from the same full-rail curves;
|
|
366
|
+
// Sizes come from the same full-rail curves; edge fills never crawl
|
|
337
367
|
// (filtered in deriveTargetBoundary).
|
|
338
|
-
// Both edges anchor at the live grid's own edge (
|
|
368
|
+
// Both edges anchor at the live grid's own edge (edgeAnchors),
|
|
339
369
|
// which is the same pair deriveTargetBoundary classified against.
|
|
340
|
-
const
|
|
341
|
-
const
|
|
342
|
-
const buySlotsAll = [...buySlots, ...
|
|
343
|
-
const sellSlotsAll = [...sellSlots, ...
|
|
370
|
+
const edgeBuySlots = selectEdgeSlots(allBuySortedForSizing.filter((s) => inBuyRail(s)), resolveEdgeCount(config, 'buy'), new Set(buySlots.map((s) => s.id)), 'floor', edgeAnchors.buy);
|
|
371
|
+
const edgeSellSlots = selectEdgeSlots(allSellSortedForSizing.filter((s) => inSellRail(s)), resolveEdgeCount(config, 'sell'), new Set(sellSlots.map((s) => s.id)), 'ceiling', edgeAnchors.sell);
|
|
372
|
+
const buySlotsAll = [...buySlots, ...edgeBuySlots];
|
|
373
|
+
const sellSlotsAll = [...sellSlots, ...edgeSellSlots];
|
|
344
374
|
const buySizes = buySlotsAll.map((slot) => buySizeById.get(slot.id) || 0);
|
|
345
375
|
const sellSizes = sellSlotsAll.map((slot) => sellSizeById.get(slot.id) || 0);
|
|
346
376
|
// Apply sizes to target grid map
|
|
@@ -123,7 +123,7 @@ function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
|
|
|
123
123
|
const { BitShares } = client;
|
|
124
124
|
import { NATIVE_CLIENT } from '../constants.js';
|
|
125
125
|
const { toFiniteNumber } = Format;
|
|
126
|
-
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual } from './utils/math.js';
|
|
126
|
+
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
|
|
127
127
|
import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
|
|
128
128
|
import { parseSlotIndex } from './utils/slot.js';
|
|
129
129
|
import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
|
|
@@ -228,7 +228,7 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
|
|
|
228
228
|
const priceDiff = Math.abs(price - chainPrice);
|
|
229
229
|
let priceEqual = false;
|
|
230
230
|
try {
|
|
231
|
-
priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision);
|
|
231
|
+
priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision, mgr?.assets, chainSize, toFiniteNumber(slot.size), chainOrder.type, mgr?.config?.incrementPercent);
|
|
232
232
|
}
|
|
233
233
|
catch {
|
|
234
234
|
priceEqual = chainPrice === price;
|
|
@@ -293,13 +293,20 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
|
|
|
293
293
|
* correction / duplicate / re-slot warranted. Unjudgeable inputs (no ladder,
|
|
294
294
|
* non-finite price) fall back to integer equality at the asset precision.
|
|
295
295
|
*/
|
|
296
|
-
function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision) {
|
|
296
|
+
function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision, assets = null, chainSize = 0, slotSize = 0, type = null, incrementPercent = null) {
|
|
297
297
|
if (hasGenesisLadder(genesis)) {
|
|
298
298
|
try {
|
|
299
299
|
const g = genesis;
|
|
300
300
|
return slotIndexForPrice(chainPrice, g) === slotIndexForPrice(slotPrice, g);
|
|
301
301
|
}
|
|
302
|
-
catch { /* unjudgeable — fall through to
|
|
302
|
+
catch { /* unjudgeable — fall through to price-level comparison */ }
|
|
303
|
+
}
|
|
304
|
+
// No ladder (legacy/migration window): compare the chain price to the slot
|
|
305
|
+
// price with the chain-representable tolerance, capped to half a grid step.
|
|
306
|
+
// NOT priceSlotEqual at the asset amount precision, which collapses
|
|
307
|
+
// adjacent levels for a low-precision asset.
|
|
308
|
+
if (assets != null) {
|
|
309
|
+
return pricesOnSameLevel(chainPrice, chainSize, type, slotPrice, slotSize, type, assets, incrementPercent);
|
|
303
310
|
}
|
|
304
311
|
try {
|
|
305
312
|
return priceSlotEqual(chainPrice, slotPrice, precision);
|
|
@@ -651,6 +658,10 @@ class SyncEngine {
|
|
|
651
658
|
? (innerResult.unmatchedChainOrders ?? []).map((order) => ({ ...order }))
|
|
652
659
|
: [];
|
|
653
660
|
mgr._lastUnmatchedChainOrdersAt = unmatchedCount > 0 ? Date.now() : 0;
|
|
661
|
+
// Freshness stamp for the spread-correction bypass gate:
|
|
662
|
+
// only a completed open-orders sync makes the local anchor
|
|
663
|
+
// trustworthy enough to bypass the LAST-FILL-GUARD.
|
|
664
|
+
mgr._lastSyncAt = Date.now();
|
|
654
665
|
mgr.logger?.log?.(`[SYNC] Synchronization complete: ${innerResult.filledOrders.length} filled, ` +
|
|
655
666
|
`${innerResult.updatedOrders.length} updated, ` +
|
|
656
667
|
`${innerResult.ordersNeedingCorrection.length} needing correction.`, 'info');
|
|
@@ -971,7 +982,7 @@ class SyncEngine {
|
|
|
971
982
|
// drift of a few quanta inside one level is normal and must
|
|
972
983
|
// not queue a price correction.
|
|
973
984
|
const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
|
|
974
|
-
const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision);
|
|
985
|
+
const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(chainOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent);
|
|
975
986
|
if (!isPriceEqual) {
|
|
976
987
|
queueCorrection({
|
|
977
988
|
gridOrder: { ...gridOrder },
|
|
@@ -1013,7 +1024,7 @@ class SyncEngine {
|
|
|
1013
1024
|
// ladder level as the slot (the swap tiebreak's whole
|
|
1014
1025
|
// premise — a duplicate at this level).
|
|
1015
1026
|
const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
|
|
1016
|
-
if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision))
|
|
1027
|
+
if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(candidateOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent))
|
|
1017
1028
|
continue;
|
|
1018
1029
|
if (floatToBlockchainInt(candidateOrder.size, precision) !== currentSizeInt)
|
|
1019
1030
|
continue;
|
|
@@ -1227,8 +1238,7 @@ class SyncEngine {
|
|
|
1227
1238
|
// (no adopt, no cancelOnly), e.g. dip-protection levels
|
|
1228
1239
|
// sitting below a fresh grid after a reset.
|
|
1229
1240
|
{
|
|
1230
|
-
|
|
1231
|
-
if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, precision)) {
|
|
1241
|
+
if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, toFiniteNumber(chainOrder.size), chainOrder.type, mgr.assets)) {
|
|
1232
1242
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
|
|
1233
1243
|
mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: price outside grid range, deferred (nearest slot ${slotId})`, 'warn');
|
|
1234
1244
|
continue;
|
|
@@ -1244,7 +1254,10 @@ class SyncEngine {
|
|
|
1244
1254
|
// legitimate in-rail orphan waits one sync cycle
|
|
1245
1255
|
// post-boundary-commit before adoption. Strictly better than
|
|
1246
1256
|
// adopting a gap stray into the wrong slot.
|
|
1247
|
-
|
|
1257
|
+
// '' guard: Number('') === 0 is finite, so an empty-string
|
|
1258
|
+
// boundary would read as boundary 0 (same trap guarded in
|
|
1259
|
+
// runPreBroadcastGuards / resolveGapBand).
|
|
1260
|
+
if (boundaryIdx == null || boundaryIdx === '' || !Number.isFinite(Number(boundaryIdx))) {
|
|
1248
1261
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'boundary-unknown-deferred', candidateSlotId: slotId });
|
|
1249
1262
|
mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: boundary unknown, deferred until boundary commits (nearest slot ${slotId})`, 'warn');
|
|
1250
1263
|
continue;
|