dexbot 1.6.18 → 1.7.0
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 +26 -0
- package/README.md +24 -18
- package/analysis/README.md +95 -3
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/analyze_dynamic_weight.js +2 -1
- package/dist/analysis/analyze_kalman.js +3 -2
- package/dist/analysis/analyze_liquidity.d.ts +17 -0
- package/dist/analysis/analyze_liquidity.js +325 -0
- package/dist/analysis/analyze_regime.js +3 -2
- package/dist/analysis/analyze_regime_windows.js +3 -2
- package/dist/analysis/analyze_volatility.js +3 -2
- package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
- package/dist/analysis/liquidity/liquidity_chain.js +178 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
- package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
- package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
- package/dist/analysis/liquidity/liquidity_view.js +55 -0
- package/dist/analysis/trade_profitability.js +2 -1
- package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
- package/dist/dexbot.js +74 -169
- package/dist/modules/asset_lookup.d.ts +25 -0
- package/dist/modules/asset_lookup.js +75 -0
- package/dist/modules/chain_scan.d.ts +64 -0
- package/dist/modules/chain_scan.js +80 -0
- package/dist/modules/cli_colors.d.ts +5 -0
- package/dist/modules/cli_colors.js +7 -0
- package/dist/modules/cli_progress.d.ts +51 -0
- package/dist/modules/cli_progress.js +113 -0
- package/dist/modules/dexbot_cow_runtime.js +14 -4
- package/dist/modules/dexbot_fill_runtime.js +20 -0
- package/dist/modules/dexbot_maintenance_runtime.js +16 -1
- package/dist/modules/launcher/runtime_entry.d.ts +21 -1
- package/dist/modules/launcher/runtime_entry.js +36 -1
- package/dist/modules/liquidity_pool_ref.d.ts +32 -0
- package/dist/modules/liquidity_pool_ref.js +116 -0
- package/dist/modules/order/grid.js +9 -2
- package/dist/modules/order/grid_reconcile.js +22 -1
- package/dist/modules/order/grid_reconcile_internal.js +92 -14
- package/dist/modules/order/index.d.ts +15 -1
- package/dist/modules/order/manager.d.ts +2 -0
- package/dist/modules/order/manager.js +3 -0
- package/dist/modules/order/sync_engine.d.ts +20 -0
- package/dist/modules/order/sync_engine.js +101 -33
- package/dist/modules/order/utils/math.d.ts +18 -1
- package/dist/modules/order/utils/math.js +30 -1
- package/dist/modules/order/utils/order.d.ts +107 -1
- package/dist/modules/order/utils/order.js +298 -1
- package/dist/modules/order/utils/system.d.ts +63 -1
- package/dist/modules/order/utils/system.js +247 -36
- package/dist/modules/order/utils/validate.js +33 -2
- package/dist/modules/types.d.ts +5 -0
- package/dist/modules/utils/asset_symbols.d.ts +13 -2
- package/dist/modules/utils/asset_symbols.js +21 -2
- package/dist/scripts/analysis_runner.d.ts +10 -0
- package/dist/scripts/analysis_runner.js +33 -0
- package/dist/scripts/analyze-orders.js +2 -1
- package/dist/scripts/asset.d.ts +26 -0
- package/dist/scripts/asset.js +165 -0
- package/dist/scripts/bts_distribution.d.ts +1 -0
- package/dist/scripts/bts_distribution.js +194 -142
- package/dist/scripts/chart_command.d.ts +1 -1
- package/dist/scripts/chart_command.js +60 -86
- package/dist/scripts/chart_targets.d.ts +18 -0
- package/dist/scripts/chart_targets.js +52 -0
- package/dist/scripts/dw.js +1 -1
- package/dist/scripts/liquid.d.ts +24 -0
- package/dist/scripts/liquid.js +134 -0
- package/dist/scripts/rich_list.js +12 -16
- package/dist/scripts/token_distribution.d.ts +2 -0
- package/dist/scripts/token_distribution.js +132 -108
- package/dist/scripts/tv.js +1 -1
- package/dist/scripts/verify-browser-bundle.js +18 -0
- package/docs/COW_INVARIANTS.md +2 -2
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +9 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +4 -1
- package/docs/GRID_RECONCILE.md +20 -0
- package/docs/LOGGING.md +25 -3
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +2 -1
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +3 -1
- package/modules/README.md +5 -1
- package/package.json +3 -1
- package/scripts/README.md +23 -7
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { ORDER_TYPES, ORDER_STATES, TIMING, BTS_PRECISION } from '../constants.js';
|
|
8
8
|
import { readOpenOrdersGuarded } from '../chain_orders.js';
|
|
9
|
-
import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, sameGridLevel } from './utils/math.js';
|
|
9
|
+
import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, pricesWithinHalfStep, sameGridLevel } from './utils/math.js';
|
|
10
10
|
import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
|
|
11
11
|
import { parseSlotIndex } from './utils/slot.js';
|
|
12
|
-
import { resolveAccountRef } from './utils/system.js';
|
|
12
|
+
import { resolveAccountRef, isLastFillPlacementBlocked, hasUnsettledFills } from './utils/system.js';
|
|
13
13
|
import * as Format from './format.js';
|
|
14
14
|
import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
|
|
15
15
|
function computePlacementPriceCollision(manager, gridOrder) {
|
|
@@ -206,6 +206,15 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
|
|
|
206
206
|
// Derived budgeted size per slot, built once (O(n)) so below-min lookups
|
|
207
207
|
// don't recompute full-side sizing for every candidate (avoid O(n²)).
|
|
208
208
|
const derivedSizes = _deriveBudgetedSideSizes(manager, type);
|
|
209
|
+
// LAST-FILL placement discipline at PICK time: a candidate on the wrong
|
|
210
|
+
// side of the last fill (or on its own level) must not consume activation
|
|
211
|
+
// budget — the create would be refused downstream anyway, and the pick
|
|
212
|
+
// budget is what decides which levels get restored. Skipping it lets the
|
|
213
|
+
// picker fall through to the NEXT level down (BUY) / up (SELL), which is
|
|
214
|
+
// the "rotate to the bottom BUY / counter SELL" behaviour: the level that
|
|
215
|
+
// just traded is never re-stamped same-side.
|
|
216
|
+
let lastFillSkipped = 0;
|
|
217
|
+
let lastFillPivot = null;
|
|
209
218
|
for (const slot of slotsOfType) {
|
|
210
219
|
if (valid.length >= count)
|
|
211
220
|
break;
|
|
@@ -226,6 +235,13 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
|
|
|
226
235
|
}
|
|
227
236
|
}
|
|
228
237
|
if (slot.id && effectiveSize >= effectiveMin) {
|
|
238
|
+
const fillGuard = isLastFillPlacementBlocked(manager, slot.price, type);
|
|
239
|
+
if (fillGuard.blocked) {
|
|
240
|
+
lastFillSkipped++;
|
|
241
|
+
if (lastFillPivot == null)
|
|
242
|
+
lastFillPivot = fillGuard.pivot;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
229
245
|
// Re-type the picked slot to the activation side: empty slots are
|
|
230
246
|
// stored SPREAD (side-neutral), but an order being placed here must
|
|
231
247
|
// carry the concrete BUY/SELL rail type (SPREAD+ACTIVE is illegal,
|
|
@@ -238,6 +254,10 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
|
|
|
238
254
|
}
|
|
239
255
|
}
|
|
240
256
|
}
|
|
257
|
+
if (lastFillSkipped > 0) {
|
|
258
|
+
manager.logger?.log?.(`Startup: ${type.toUpperCase()} pick skipped ${lastFillSkipped} slot(s) on the wrong side of the last fill ` +
|
|
259
|
+
`(pivot ${lastFillPivot == null ? 'n/a' : Format.formatPrice6(lastFillPivot)}); picked ${valid.length}/${count}`, 'debug');
|
|
260
|
+
}
|
|
241
261
|
return valid;
|
|
242
262
|
}
|
|
243
263
|
/**
|
|
@@ -483,6 +503,21 @@ async function _createOrderFromGrid({ chainOrders, account, privateKey, manager,
|
|
|
483
503
|
`@${Format.formatPrice6(crossed.price ?? crossed.order?.price ?? 0)}`, 'warn');
|
|
484
504
|
return null;
|
|
485
505
|
}
|
|
506
|
+
// LAST-FILL GUARD: never place a BUY on/above the price that just traded,
|
|
507
|
+
// nor a SELL on/below it (same level included — see
|
|
508
|
+
// isLastFillPlacementBlocked). The COW planner has this discipline; the
|
|
509
|
+
// reconcile/startup create path did not, so a top-up could re-create the
|
|
510
|
+
// level it had just bought at (live: 19 of 37 creates at an already-filled
|
|
511
|
+
// level, 9 of them above the previous fill). Refusing here fails closed to
|
|
512
|
+
// the next reconcile cycle, when the crawl has moved the rail.
|
|
513
|
+
const fillGuard = isLastFillPlacementBlocked(manager, createPrice, gridOrder.type);
|
|
514
|
+
if (fillGuard.blocked) {
|
|
515
|
+
manager.logger?.log?.(`[_createOrderFromGrid] SKIP (LAST-FILL-GUARD): Create for ${gridOrder.id} at ` +
|
|
516
|
+
`${Format.formatPrice6(createPrice)} on the wrong side of the last fill ` +
|
|
517
|
+
`${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason}); ` +
|
|
518
|
+
`the rail must crawl before this level is refilled`, 'warn');
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
486
521
|
// Price collision guard: reject if another placed order already exists at this price level.
|
|
487
522
|
const priceCollision = computePlacementPriceCollision(manager, gridOrder);
|
|
488
523
|
if (priceCollision) {
|
|
@@ -761,11 +796,30 @@ function _prepareStartupUpdatePlan(plan, manager, logger) {
|
|
|
761
796
|
`re-align on the next reconcile cycle.`, 'warn');
|
|
762
797
|
return null;
|
|
763
798
|
}
|
|
799
|
+
// LAST-FILL GUARD: a relocation re-prices a live order onto a different
|
|
800
|
+
// level, so it is a placement and obeys the same direction rule as a
|
|
801
|
+
// create (BUY lower, SELL higher; never the level that just traded). A
|
|
802
|
+
// same-price relocation is an ADOPTION (the chain order already rests at
|
|
803
|
+
// the target level), not a placement — it is left alone.
|
|
804
|
+
const parsedChainOrder = parseChainOrder(plan.chainOrderObj, manager.assets);
|
|
805
|
+
const chainPrice = Number(parsedChainOrder?.price);
|
|
806
|
+
const samePriceAdoption = Number.isFinite(chainPrice)
|
|
807
|
+
&& pricesWithinHalfStep(chainPrice, Number(gridOrder.price), manager.config?.incrementPercent);
|
|
808
|
+
if (!samePriceAdoption) {
|
|
809
|
+
const fillGuard = isLastFillPlacementBlocked(manager, gridOrder.price, gridOrder.type);
|
|
810
|
+
if (fillGuard.blocked) {
|
|
811
|
+
logger?.log?.(`[STARTUP-LAST-FILL-GUARD] Skipping relocation update ${chainOrderId} -> ${gridOrder.id}: ` +
|
|
812
|
+
`target ${gridOrder.type} @${Format.formatPrice6(gridOrder.price)} is on the wrong side of the ` +
|
|
813
|
+
`last fill ${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason}); ` +
|
|
814
|
+
`re-align on the next reconcile cycle.`, 'warn');
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
764
818
|
return {
|
|
765
819
|
plan,
|
|
766
820
|
chainOrderId,
|
|
767
821
|
gridOrder,
|
|
768
|
-
parsedChain:
|
|
822
|
+
parsedChain: parsedChainOrder,
|
|
769
823
|
updateParams: {
|
|
770
824
|
newPrice: gridOrder.price,
|
|
771
825
|
amountToSell,
|
|
@@ -1152,6 +1206,16 @@ async function _executeStartupCreateGroupBatch({ group, chainOrders, account, pr
|
|
|
1152
1206
|
`@${Format.formatPrice6(crossed.price ?? crossed.order?.price ?? 0)}`, 'warn');
|
|
1153
1207
|
continue;
|
|
1154
1208
|
}
|
|
1209
|
+
// LAST-FILL GUARD: creates only — never restore a level on the wrong
|
|
1210
|
+
// side of the last fill (includes the level that just traded). See
|
|
1211
|
+
// isLastFillPlacementBlocked.
|
|
1212
|
+
const fillGuard = isLastFillPlacementBlocked(manager, createPrice, gridOrder.type);
|
|
1213
|
+
if (fillGuard.blocked) {
|
|
1214
|
+
logger?.log?.(`Startup: Skip create ${plan.orderLabel} (LAST-FILL-GUARD) - price ` +
|
|
1215
|
+
`${Format.formatPrice6(createPrice)} is on the wrong side of the last fill ` +
|
|
1216
|
+
`${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason})`, 'warn');
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1155
1219
|
const { amountToSell, sellAssetId, minToReceive, receiveAssetId } = buildCreateOrderArgs(gridOrder, manager.assets.assetA, manager.assets.assetB);
|
|
1156
1220
|
// GRID-PRICE-INVARIANT (blocking): see docs/GRID_PRICE_INVARIANT.md.
|
|
1157
1221
|
if (!reportGridPriceInvariant(manager, gridOrder?.id, gridOrder?.price, 'STARTUP-CREATE')) {
|
|
@@ -1609,17 +1673,31 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
|
|
|
1609
1673
|
catch { /* fail-open: keep unfiltered count */ }
|
|
1610
1674
|
const createCount = Math.max(0, targetCount - chainCount);
|
|
1611
1675
|
const remainingSlots = desiredSlots.slice(updateCount);
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1676
|
+
// UNSETTLED-FILL GATE: while fills are queued, draining, in flight, or
|
|
1677
|
+
// owed a crawl, the master still treats filled slots as ACTIVE and the
|
|
1678
|
+
// boundary has not crawled for them. Any window top-up derived from that
|
|
1679
|
+
// geometry refills the EXPENSIVE end of the rail — the live incident
|
|
1680
|
+
// (12s of buys at 1282.78 -> 1310.04 while the market was ~1280). Defer
|
|
1681
|
+
// the top-up to the cycle after the fills (and their crawl) are committed;
|
|
1682
|
+
// 1:1 repairs (cancelled-slot replacement, vacated-rail refill) still run.
|
|
1683
|
+
const unsettled = hasUnsettledFills(manager);
|
|
1684
|
+
if (unsettled.unsettled && createCount > 0) {
|
|
1685
|
+
logger?.log?.(`Startup: Deferring ${Math.min(createCount, remainingSlots.length)} ${sideUpper} window top-up create(s): ` +
|
|
1686
|
+
`${unsettled.reason} — the rail must absorb the fills before it is refilled`, 'warn');
|
|
1687
|
+
}
|
|
1688
|
+
else {
|
|
1689
|
+
for (let i = 0; i < Math.min(createCount, remainingSlots.length); i++) {
|
|
1690
|
+
const gridOrder = remainingSlots[i];
|
|
1691
|
+
logger?.log?.(`Startup: Creating ${sideUpper} for grid ${gridOrder.id} (price=${Format.formatPrice6(gridOrder.price)}, size=${Format.formatSizeByOrderType(gridOrder.size, orderType, manager.assets)})`, 'info');
|
|
1692
|
+
plannedCreates.push({
|
|
1693
|
+
orderType,
|
|
1694
|
+
gridOrder,
|
|
1695
|
+
orderLabel: sideUpper,
|
|
1696
|
+
// Intentionally no recovery metadata here.
|
|
1697
|
+
// This preserves legacy behavior: regular virtual-slot creates only log failures,
|
|
1698
|
+
// while cancelled-slot replacement creates trigger a startup recovery sync.
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1623
1701
|
}
|
|
1624
1702
|
// Guard: when the matcher found zero active grid orders (matchedOnGrid === 0)
|
|
1625
1703
|
// AND we're actively scaling up (neededSlots > 0), the grid is freshly
|
|
@@ -99,7 +99,7 @@ declare const utils: {
|
|
|
99
99
|
fillSlot?: number;
|
|
100
100
|
reason?: string;
|
|
101
101
|
};
|
|
102
|
-
resolveLastFillGuardReference(manager: import("../types.js").OrderManagerLike): {
|
|
102
|
+
resolveLastFillGuardReference(manager: import("../types.js").OrderManagerLike | null | undefined): {
|
|
103
103
|
price: number | null;
|
|
104
104
|
type: string | null;
|
|
105
105
|
};
|
|
@@ -108,6 +108,15 @@ declare const utils: {
|
|
|
108
108
|
pivot: number | null;
|
|
109
109
|
threshold?: number | null;
|
|
110
110
|
};
|
|
111
|
+
isLastFillPlacementBlocked(manager: import("../types.js").OrderManagerLike | null | undefined, price: unknown, type: unknown): {
|
|
112
|
+
blocked: boolean;
|
|
113
|
+
pivot: number | null;
|
|
114
|
+
reason?: "direction" | "same-level";
|
|
115
|
+
};
|
|
116
|
+
hasUnsettledFills(source: unknown): {
|
|
117
|
+
unsettled: boolean;
|
|
118
|
+
reason: string | null;
|
|
119
|
+
};
|
|
111
120
|
restoreLastMarketFill(manager: import("../types.js").OrderManagerLike, persisted: unknown, options?: {
|
|
112
121
|
now?: number;
|
|
113
122
|
}): boolean;
|
|
@@ -198,6 +207,10 @@ declare const utils: {
|
|
|
198
207
|
parseChainOrder: typeof order.parseChainOrder;
|
|
199
208
|
resolveLiveOrderLadderPosition: typeof order.resolveLiveOrderLadderPosition;
|
|
200
209
|
applyChainSizeToGridOrder: typeof order.applyChainSizeToGridOrder;
|
|
210
|
+
resolveExecutionPrice: typeof order.resolveExecutionPrice;
|
|
211
|
+
resolveSlotIdForFillPrice: typeof order.resolveSlotIdForFillPrice;
|
|
212
|
+
reviveVirtualSlotFromChain: typeof order.reviveVirtualSlotFromChain;
|
|
213
|
+
attributeUnmatchedFillToGrid: typeof order.attributeUnmatchedFillToGrid;
|
|
201
214
|
buildFillKey: typeof order.buildFillKey;
|
|
202
215
|
correctOrderPriceOnChain: typeof order.correctOrderPriceOnChain;
|
|
203
216
|
correctAllPriceMismatches: typeof order.correctAllPriceMismatches;
|
|
@@ -346,6 +359,7 @@ declare const utils: {
|
|
|
346
359
|
priceSlotEqual: typeof math.priceSlotEqual;
|
|
347
360
|
derivePriceLevels: typeof math.derivePriceLevels;
|
|
348
361
|
sameGridLevel: typeof math.sameGridLevel;
|
|
362
|
+
pricesWithinHalfStep: typeof math.pricesWithinHalfStep;
|
|
349
363
|
buildGenesisFromPriceLevels: typeof math.buildGenesisFromPriceLevels;
|
|
350
364
|
hashPriceLevels: typeof math.hashPriceLevels;
|
|
351
365
|
isChainPriceOutOfGrid: typeof math.isChainPriceOutOfGrid;
|
|
@@ -219,6 +219,8 @@ declare class OrderManager implements OrderManagerLike {
|
|
|
219
219
|
_lastFilledPrice: number | null;
|
|
220
220
|
_lastFilledType: string | null;
|
|
221
221
|
_lastFilledAt: number;
|
|
222
|
+
/** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
|
|
223
|
+
_lastFillPivotExpiryLoggedAt: number;
|
|
222
224
|
lastFillPivotSource: 'fill' | 'book' | null;
|
|
223
225
|
_lastMarketFillPrice: number | null;
|
|
224
226
|
_lastMarketFillType: string | null;
|
|
@@ -436,6 +436,8 @@ class OrderManager {
|
|
|
436
436
|
_lastFilledPrice;
|
|
437
437
|
_lastFilledType;
|
|
438
438
|
_lastFilledAt;
|
|
439
|
+
/** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
|
|
440
|
+
_lastFillPivotExpiryLoggedAt;
|
|
439
441
|
lastFillPivotSource;
|
|
440
442
|
// Bot-scoped "last market fill" reference. Unlike the genesis-bound
|
|
441
443
|
// LAST-FILL-GUARD pivot (reset with the grid generation), this survives a
|
|
@@ -584,6 +586,7 @@ class OrderManager {
|
|
|
584
586
|
this._lastFilledPrice = null;
|
|
585
587
|
this._lastFilledType = null;
|
|
586
588
|
this._lastFilledAt = 0;
|
|
589
|
+
this._lastFillPivotExpiryLoggedAt = 0;
|
|
587
590
|
// Pivot provenance for the LAST-FILL-GUARD persist/restore contract:
|
|
588
591
|
// 'fill' = armed by a real fill (persist-eligible), 'book' = armed by
|
|
589
592
|
// the startup book seed (heuristic, in-memory only), null = unarmed.
|
|
@@ -300,6 +300,26 @@ declare class SyncEngine {
|
|
|
300
300
|
unmatchedChainOrders: UnmatchedChainOrder[];
|
|
301
301
|
}>;
|
|
302
302
|
_findMatchingGridOrder(mgr: OrderManagerLike, orderId: string | null | undefined): ManagedOrder | null;
|
|
303
|
+
/**
|
|
304
|
+
* Absorb a fill whose order id has no ACTIVE/PARTIAL slot ("order not found
|
|
305
|
+
* in active grid").
|
|
306
|
+
*
|
|
307
|
+
* Thin wrapper over the shared `attributeUnmatchedFillToGrid` helper (see
|
|
308
|
+
* utils/order.ts for the two identities and the incident it closes). The
|
|
309
|
+
* work lives outside this class so the orphan-credit path in
|
|
310
|
+
* dexbot_fill_runtime.ts attributes fills with literally the same rule
|
|
311
|
+
* instead of keeping a second, weaker copy.
|
|
312
|
+
*
|
|
313
|
+
* @returns {boolean} true when the fill was attributed to the grid.
|
|
314
|
+
*/
|
|
315
|
+
_absorbUnmatchedFill(mgr: OrderManagerLike, params: {
|
|
316
|
+
orderId: string | null | undefined;
|
|
317
|
+
paysAssetId?: string | null;
|
|
318
|
+
paysAmountRaw?: unknown;
|
|
319
|
+
receivesAssetId?: string | null;
|
|
320
|
+
receivesAmountRaw?: unknown;
|
|
321
|
+
isPartial?: boolean;
|
|
322
|
+
}): boolean;
|
|
303
323
|
_computeFillContext(mgr: OrderManagerLike, matchedGridOrder: ManagedOrder, paysAssetId: string | null | undefined, paysAmountRaw: number, receivesAssetId?: string | null | undefined, receivesAmountRaw?: number | null): {
|
|
304
324
|
orderType: OrderType;
|
|
305
325
|
currentSize: number;
|
|
@@ -139,7 +139,7 @@ const { BitShares } = client;
|
|
|
139
139
|
import { NATIVE_CLIENT } from '../constants.js';
|
|
140
140
|
const { toFiniteNumber } = Format;
|
|
141
141
|
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
|
|
142
|
-
import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
|
|
142
|
+
import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders, attributeUnmatchedFillToGrid, reviveVirtualSlotFromChain, resolveExecutionPrice } from './utils/order.js';
|
|
143
143
|
import { parseSlotIndex } from './utils/slot.js';
|
|
144
144
|
import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
|
|
145
145
|
import { hasGenesisLadder } from './genesis_policy.js';
|
|
@@ -972,6 +972,23 @@ class SyncEngine {
|
|
|
972
972
|
continue;
|
|
973
973
|
let updatedOrder = { ...gridOrder };
|
|
974
974
|
chainOrderIdsOnGrid.add(gridOrder.orderId);
|
|
975
|
+
// REVIVE BEFORE ANYTHING ELSE: this slot is not placed but its
|
|
976
|
+
// chain order is still live. Leaving it VIRTUAL is the "dark
|
|
977
|
+
// level" state — invisible to window accounting
|
|
978
|
+
// (_countActiveOnGrid needs ACTIVE/PARTIAL) while its order is
|
|
979
|
+
// still counted in chainCount, so the reconcile reads a
|
|
980
|
+
// shortfall it can never repair and the planner sees a free
|
|
981
|
+
// level that already holds an order. The revive is master-only
|
|
982
|
+
// (no broadcast) and refuses when the chain order does not rest
|
|
983
|
+
// at this slot's level, so a rotation source whose cancel has
|
|
984
|
+
// not landed is NOT resurrected.
|
|
985
|
+
if (!isOrderPlaced(gridOrder)) {
|
|
986
|
+
const revived = await reviveVirtualSlotFromChain(mgr, gridOrder, chainOrder, rawChainOrders.get(gridOrder.orderId), 'sync-pass1-revive', { skipAccounting });
|
|
987
|
+
if (revived) {
|
|
988
|
+
updatedOrders.push(revived);
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
975
992
|
// Store raw blockchain data in grid slot for later update calculation.
|
|
976
993
|
// Tag the snapshot with `fetchedAt` so the drift check in
|
|
977
994
|
// syncFromFillHistory can distinguish a fresh chain read from a
|
|
@@ -1187,7 +1204,16 @@ class SyncEngine {
|
|
|
1187
1204
|
}
|
|
1188
1205
|
}
|
|
1189
1206
|
}
|
|
1190
|
-
else if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL) {
|
|
1207
|
+
else if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL || hasOnChainId(gridOrder)) {
|
|
1208
|
+
// Also entered for a NON-placed slot that still carries an
|
|
1209
|
+
// orderId (virtualised while its order was live). Two outcomes
|
|
1210
|
+
// below, decided by `wasPlaced`:
|
|
1211
|
+
// * placed + absent -> a real fill/phantom (booked as before),
|
|
1212
|
+
// * virtual + absent -> the id is simply STALE: clear it so the
|
|
1213
|
+
// level becomes a normal hole again. Without this a stale id
|
|
1214
|
+
// would keep the slot looking occupied forever (blocking the
|
|
1215
|
+
// CREATE that the level needs) and would keep masking a
|
|
1216
|
+
// genuine fill on the other side.
|
|
1191
1217
|
// Don't virtualize orders placed by a successful COW commit.
|
|
1192
1218
|
// The chain snapshot may lag behind confirmed transactions,
|
|
1193
1219
|
// causing correctly-placed orders to appear missing. _committedOrderIds
|
|
@@ -1229,8 +1255,23 @@ class SyncEngine {
|
|
|
1229
1255
|
}
|
|
1230
1256
|
const currentGridOrder = mgr.orders.get(gridOrder.id) || gridOrder;
|
|
1231
1257
|
const hadOrderId = Boolean(currentGridOrder?.orderId);
|
|
1258
|
+
const wasPlaced = isOrderPlaced(currentGridOrder);
|
|
1259
|
+
// A freshly assigned id on a NON-placed slot is not trustworthy
|
|
1260
|
+
// evidence of absence yet (an in-flight create/cancel whose
|
|
1261
|
+
// broadcast has not landed, or a lagging read). Mirrors the
|
|
1262
|
+
// reconcile's _orderIdAssignedAt deferral: keep the id, re-check
|
|
1263
|
+
// next sync. A PLACED slot keeps the existing behaviour.
|
|
1264
|
+
if (!wasPlaced && hadOrderId) {
|
|
1265
|
+
const assignedAt = Number(mgr._orderIdAssignedAt?.get(String(currentGridOrder.orderId)) || 0);
|
|
1266
|
+
if (assignedAt > 0 && Date.now() - assignedAt < TIMING.SYNC_LOCK_TIMEOUT_MS) {
|
|
1267
|
+
mgr.logger?.log?.(`[SYNC] Stale-id check for ${gridOrder.id} deferred: chain id ${currentGridOrder.orderId} was ` +
|
|
1268
|
+
`assigned ${Date.now() - assignedAt}ms ago and is not in the snapshot — absence not yet trustworthy`, 'debug');
|
|
1269
|
+
continue;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1232
1272
|
const spreadOrder = convertToSpreadPlaceholder(currentGridOrder);
|
|
1233
|
-
const
|
|
1273
|
+
const cleanupContext = wasPlaced ? 'sync-cleanup-phantom' : 'sync-clear-stale-id';
|
|
1274
|
+
const phantomApplied = await mgr._applyOrderUpdate(spreadOrder, cleanupContext, { skipAccounting: skipAccounting, fee: 0 });
|
|
1234
1275
|
if (phantomApplied === false) {
|
|
1235
1276
|
// Rejected virtualization books no phantom fill: the slot
|
|
1236
1277
|
// keeps its order and the disappearance re-detects next
|
|
@@ -1238,8 +1279,12 @@ class SyncEngine {
|
|
|
1238
1279
|
mgr.logger?.log?.(`[SYNC] Phantom cleanup for ${gridOrder.id} rejected — fill NOT booked`, 'warn');
|
|
1239
1280
|
continue;
|
|
1240
1281
|
}
|
|
1241
|
-
// Only genuine disappearances
|
|
1242
|
-
|
|
1282
|
+
// Only genuine disappearances of a PLACED order count as fills.
|
|
1283
|
+
// A virtualised slot's stale id is cleared above without booking
|
|
1284
|
+
// anything: the funds for that level were already settled when
|
|
1285
|
+
// the slot was virtualised, and inventing a fill here would arm
|
|
1286
|
+
// the pivot and crawl for a trade that never happened.
|
|
1287
|
+
if (hadOrderId && wasPlaced) {
|
|
1243
1288
|
// A SPREAD slot can carry an on-chain order (spread-correction
|
|
1244
1289
|
// activation). Resolve the real side before pushing: the fill
|
|
1245
1290
|
// drives deriveTargetBoundary, which only shifts on BUY/SELL —
|
|
@@ -1273,6 +1318,12 @@ class SyncEngine {
|
|
|
1273
1318
|
...(liveChainPrice != null ? { price: liveChainPrice } : {})
|
|
1274
1319
|
});
|
|
1275
1320
|
}
|
|
1321
|
+
else if (hadOrderId) {
|
|
1322
|
+
updatedOrders.push(spreadOrder);
|
|
1323
|
+
mgr.logger?.log?.(`[SYNC] Cleared stale chain id ${currentGridOrder?.orderId ?? ''} on ${gridOrder.id} ` +
|
|
1324
|
+
`(slot was ${currentGridOrder?.state ?? ORDER_STATES.VIRTUAL}): the order is gone from the ` +
|
|
1325
|
+
`chain read, so the level is a normal hole again — no fill booked`, 'debug');
|
|
1326
|
+
}
|
|
1276
1327
|
}
|
|
1277
1328
|
}
|
|
1278
1329
|
// ====================================================================
|
|
@@ -1407,6 +1458,28 @@ class SyncEngine {
|
|
|
1407
1458
|
}
|
|
1408
1459
|
return null;
|
|
1409
1460
|
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Absorb a fill whose order id has no ACTIVE/PARTIAL slot ("order not found
|
|
1463
|
+
* in active grid").
|
|
1464
|
+
*
|
|
1465
|
+
* Thin wrapper over the shared `attributeUnmatchedFillToGrid` helper (see
|
|
1466
|
+
* utils/order.ts for the two identities and the incident it closes). The
|
|
1467
|
+
* work lives outside this class so the orphan-credit path in
|
|
1468
|
+
* dexbot_fill_runtime.ts attributes fills with literally the same rule
|
|
1469
|
+
* instead of keeping a second, weaker copy.
|
|
1470
|
+
*
|
|
1471
|
+
* @returns {boolean} true when the fill was attributed to the grid.
|
|
1472
|
+
*/
|
|
1473
|
+
_absorbUnmatchedFill(mgr, params) {
|
|
1474
|
+
return attributeUnmatchedFillToGrid(mgr, {
|
|
1475
|
+
orderId: params?.orderId ?? null,
|
|
1476
|
+
paysAssetId: params?.paysAssetId ?? null,
|
|
1477
|
+
paysAmountRaw: params?.paysAmountRaw == null ? null : Number(params.paysAmountRaw),
|
|
1478
|
+
receivesAssetId: params?.receivesAssetId ?? null,
|
|
1479
|
+
receivesAmountRaw: params?.receivesAmountRaw == null ? null : Number(params.receivesAmountRaw),
|
|
1480
|
+
isPartial: params?.isPartial === true,
|
|
1481
|
+
});
|
|
1482
|
+
}
|
|
1410
1483
|
_computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId = null, receivesAmountRaw = null) {
|
|
1411
1484
|
const assets = mgr.assets;
|
|
1412
1485
|
if (!assets?.assetA || !assets?.assetB)
|
|
@@ -1445,32 +1518,9 @@ class SyncEngine {
|
|
|
1445
1518
|
// Execution price from the actual paid/received amounts (quote per
|
|
1446
1519
|
// base). This is the fill FACT the last-fill pivot and the re-anchor
|
|
1447
1520
|
// need; the slot price is only a grid identity and may be stale after
|
|
1448
|
-
// a refused-commit chain adoption.
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
&& Number.isFinite(Number(paysAmountRaw)) && Number(paysAmountRaw) > 0) {
|
|
1452
|
-
const A = assets.assetA;
|
|
1453
|
-
const B = assets.assetB;
|
|
1454
|
-
let baseRaw = null;
|
|
1455
|
-
let quoteRaw = null;
|
|
1456
|
-
if (paysAssetId === A.id && receivesAssetId === B.id) {
|
|
1457
|
-
baseRaw = Number(paysAmountRaw);
|
|
1458
|
-
quoteRaw = Number(receivesAmountRaw);
|
|
1459
|
-
}
|
|
1460
|
-
else if (paysAssetId === B.id && receivesAssetId === A.id) {
|
|
1461
|
-
baseRaw = Number(receivesAmountRaw);
|
|
1462
|
-
quoteRaw = Number(paysAmountRaw);
|
|
1463
|
-
}
|
|
1464
|
-
if (baseRaw !== null && quoteRaw !== null) {
|
|
1465
|
-
const base = blockchainToFloat(baseRaw, A.precision);
|
|
1466
|
-
const quote = blockchainToFloat(quoteRaw, B.precision);
|
|
1467
|
-
if (base > 0 && quote > 0) {
|
|
1468
|
-
const price = quote / base;
|
|
1469
|
-
if (Number.isFinite(price) && price > 0)
|
|
1470
|
-
fillPrice = price;
|
|
1471
|
-
}
|
|
1472
|
-
}
|
|
1473
|
-
}
|
|
1521
|
+
// a refused-commit chain adoption. Shared with the unmatched-fill
|
|
1522
|
+
// attribution so both resolve a price identically.
|
|
1523
|
+
const fillPrice = resolveExecutionPrice(assets, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
|
|
1474
1524
|
return { orderType, currentSize, precision, filledAmount, currentSizeIntFromGrid, rawForSaleInt, driftSignal, fillPrice };
|
|
1475
1525
|
}
|
|
1476
1526
|
async _computeFillTransitionResult(mgr, params) {
|
|
@@ -1682,7 +1732,16 @@ class SyncEngine {
|
|
|
1682
1732
|
}
|
|
1683
1733
|
const matchedGridOrder = this._findMatchingGridOrder(mgr, orderId);
|
|
1684
1734
|
if (!matchedGridOrder) {
|
|
1685
|
-
|
|
1735
|
+
// An order that filled while its slot was already virtualised
|
|
1736
|
+
// still proves a trade: absorb the pivot + owed crawl from the
|
|
1737
|
+
// real execution price instead of dropping it (see
|
|
1738
|
+
// _absorbUnmatchedFill). Only a truly unknown order is ignored.
|
|
1739
|
+
const absorbed = this._absorbUnmatchedFill(mgr, {
|
|
1740
|
+
orderId, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw,
|
|
1741
|
+
});
|
|
1742
|
+
if (!absorbed) {
|
|
1743
|
+
mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
|
|
1744
|
+
}
|
|
1686
1745
|
return { filledOrders: [], updatedOrders: [], partialFill: false };
|
|
1687
1746
|
}
|
|
1688
1747
|
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
|
|
@@ -1881,7 +1940,16 @@ class SyncEngine {
|
|
|
1881
1940
|
const { orderId, paysAmountRaw, paysAssetId } = entry;
|
|
1882
1941
|
const matchedGridOrder = this._findMatchingGridOrder(mgr, orderId);
|
|
1883
1942
|
if (!matchedGridOrder) {
|
|
1884
|
-
|
|
1943
|
+
// Same absorption as the single-fill path: keep the
|
|
1944
|
+
// pivot/crawl ledger honest so the next derivation and the
|
|
1945
|
+
// LAST-FILL-GUARD see the price that actually traded.
|
|
1946
|
+
const absorbed = this._absorbUnmatchedFill(mgr, {
|
|
1947
|
+
orderId, paysAssetId, paysAmountRaw,
|
|
1948
|
+
receivesAssetId: entry.receivesAssetId, receivesAmountRaw: entry.receivesAmountRaw,
|
|
1949
|
+
});
|
|
1950
|
+
if (!absorbed) {
|
|
1951
|
+
mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
|
|
1952
|
+
}
|
|
1885
1953
|
anyRequiresSync = true;
|
|
1886
1954
|
continue;
|
|
1887
1955
|
}
|
|
@@ -1253,9 +1253,26 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
|
|
|
1253
1253
|
* one that prevents non-termination, which no caller could recover from.
|
|
1254
1254
|
*/
|
|
1255
1255
|
declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
|
|
1256
|
+
/**
|
|
1257
|
+
* True when two prices are the SAME grid step: within half an increment of
|
|
1258
|
+
* each other. Used to judge a placement against the price that just traded —
|
|
1259
|
+
* a fill's execution price and the slot level it filled at differ by rounding
|
|
1260
|
+
* (live: slot 1310.046339 filled at 1310.060435, i.e. ~1e-5), so a raw
|
|
1261
|
+
* `>=`/`<=` comparison lets a same-level re-place through.
|
|
1262
|
+
*
|
|
1263
|
+
* The half-step cap mirrors `pricesOnSameLevel`: it can never merge two
|
|
1264
|
+
* legitimately adjacent levels (a full increment apart). A missing/invalid
|
|
1265
|
+
* increment degrades to exact equality.
|
|
1266
|
+
*
|
|
1267
|
+
* @param {number} priceA - First price
|
|
1268
|
+
* @param {number} priceB - Second price
|
|
1269
|
+
* @param {number} incrementPercent - Grid step in percent (e.g. 0.3)
|
|
1270
|
+
* @returns {boolean} True when both prices sit on the same grid step
|
|
1271
|
+
*/
|
|
1272
|
+
declare function pricesWithinHalfStep(priceA: number, priceB: number, incrementPercent: number | null | undefined): boolean;
|
|
1256
1273
|
declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
|
|
1257
1274
|
export type { FeeCacheEntry };
|
|
1258
|
-
export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
|
|
1275
|
+
export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
|
|
1259
1276
|
/**
|
|
1260
1277
|
* Round a value to a given factor.
|
|
1261
1278
|
* @param {number} value - Value to round
|
|
@@ -2148,6 +2148,35 @@ function derivePriceLevels(startPrice, minPrice, maxPrice, incrementPercent) {
|
|
|
2148
2148
|
}
|
|
2149
2149
|
return deduped;
|
|
2150
2150
|
}
|
|
2151
|
+
/**
|
|
2152
|
+
* True when two prices are the SAME grid step: within half an increment of
|
|
2153
|
+
* each other. Used to judge a placement against the price that just traded —
|
|
2154
|
+
* a fill's execution price and the slot level it filled at differ by rounding
|
|
2155
|
+
* (live: slot 1310.046339 filled at 1310.060435, i.e. ~1e-5), so a raw
|
|
2156
|
+
* `>=`/`<=` comparison lets a same-level re-place through.
|
|
2157
|
+
*
|
|
2158
|
+
* The half-step cap mirrors `pricesOnSameLevel`: it can never merge two
|
|
2159
|
+
* legitimately adjacent levels (a full increment apart). A missing/invalid
|
|
2160
|
+
* increment degrades to exact equality.
|
|
2161
|
+
*
|
|
2162
|
+
* @param {number} priceA - First price
|
|
2163
|
+
* @param {number} priceB - Second price
|
|
2164
|
+
* @param {number} incrementPercent - Grid step in percent (e.g. 0.3)
|
|
2165
|
+
* @returns {boolean} True when both prices sit on the same grid step
|
|
2166
|
+
*/
|
|
2167
|
+
function pricesWithinHalfStep(priceA, priceB, incrementPercent) {
|
|
2168
|
+
const pa = Number(priceA);
|
|
2169
|
+
const pb = Number(priceB);
|
|
2170
|
+
if (!Number.isFinite(pa) || !Number.isFinite(pb))
|
|
2171
|
+
return false;
|
|
2172
|
+
const inc = Number(incrementPercent);
|
|
2173
|
+
if (!Number.isFinite(inc) || inc <= 0)
|
|
2174
|
+
return pa === pb;
|
|
2175
|
+
const level = Math.min(Math.abs(pa), Math.abs(pb));
|
|
2176
|
+
if (!Number.isFinite(level))
|
|
2177
|
+
return pa === pb;
|
|
2178
|
+
return Math.abs(pa - pb) <= level * (inc / 100) * 0.5;
|
|
2179
|
+
}
|
|
2151
2180
|
function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, priceLevels) {
|
|
2152
2181
|
const hash = hashPriceLevels(priceLevels);
|
|
2153
2182
|
return {
|
|
@@ -2159,7 +2188,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
|
|
|
2159
2188
|
createdAt: Date.now()
|
|
2160
2189
|
};
|
|
2161
2190
|
}
|
|
2162
|
-
export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
|
|
2191
|
+
export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
|
|
2163
2192
|
/**
|
|
2164
2193
|
* Round a value to a given factor.
|
|
2165
2194
|
* @param {number} value - Value to round
|