dexbot 1.6.17 → 1.6.18
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 +32 -0
- package/analysis/README.md +10 -9
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +3 -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_args.d.ts +2 -1
- package/dist/analysis/fills_source.d.ts +1 -8
- package/dist/analysis/fills_source.js +1 -1
- package/dist/analysis/grid_correction_check.d.ts +9 -6
- package/dist/analysis/grid_correction_check.js +56 -64
- package/dist/analysis/math_utils.d.ts +1 -1
- package/dist/analysis/trade_profitability.d.ts +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
- package/dist/market_adapter/cli_args.d.ts +6 -1
- package/dist/market_adapter/cli_args.js +16 -2
- package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
- package/dist/market_adapter/core/kibana_candles.js +3 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
- package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
- package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
- package/dist/market_adapter/inputs/window_cache.js +14 -1
- package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
- package/dist/market_adapter/lp_chart_runner.js +3 -1
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
- package/dist/market_adapter/market_adapter.d.ts +10 -2
- package/dist/market_adapter/market_adapter.js +10 -11
- package/dist/market_adapter/utils/chain.d.ts +2 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
- package/dist/market_adapter/utils/file_json_cache.js +3 -1
- package/dist/market_adapter/utils/file_lock.js +1 -1
- package/dist/market_adapter/utils/native_history.d.ts +7 -3
- package/dist/market_adapter/utils/native_history.js +3 -1
- package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/constants.js +6 -3
- package/dist/modules/dexbot_class.d.ts +8 -0
- package/dist/modules/dexbot_class.js +10 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
- package/dist/modules/dexbot_cow_runtime.js +461 -43
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +56 -9
- package/dist/modules/dexbot_startup_runtime.js +7 -1
- package/dist/modules/graceful_shutdown.d.ts +2 -2
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/launcher/runtime_mode.d.ts +4 -3
- package/dist/modules/node_manager.d.ts +1 -1
- package/dist/modules/node_manager.js +1 -1
- package/dist/modules/order/accounting.js +2 -1
- package/dist/modules/order/export.d.ts +2 -2
- package/dist/modules/order/export.js +2 -2
- package/dist/modules/order/grid.d.ts +19 -14
- package/dist/modules/order/grid.js +262 -61
- package/dist/modules/order/grid_reconcile.js +5 -1
- package/dist/modules/order/grid_reconcile_internal.js +2 -1
- package/dist/modules/order/index.d.ts +9 -3
- package/dist/modules/order/manager.d.ts +10 -0
- package/dist/modules/order/manager.js +41 -11
- package/dist/modules/order/strategy.js +22 -2
- package/dist/modules/order/sync_engine.d.ts +12 -1
- package/dist/modules/order/sync_engine.js +135 -20
- package/dist/modules/order/utils/math.d.ts +8 -9
- package/dist/modules/order/utils/math.js +24 -13
- package/dist/modules/order/utils/order.d.ts +52 -11
- package/dist/modules/order/utils/order.js +137 -21
- package/dist/modules/order/utils/system.d.ts +73 -29
- package/dist/modules/order/utils/system.js +239 -48
- package/dist/modules/order/utils/validate.d.ts +1 -0
- package/dist/modules/order/utils/validate.js +4 -1
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +9 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +20 -10
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +9 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
- package/docs/GRID_PRICE_INVARIANT.md +24 -4
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +15 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +123 -36
- package/docs/README.md +1 -1
- package/docs/architecture.md +115 -13
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +9 -4
- package/modules/README.md +18 -14
- package/package.json +4 -3
|
@@ -30,7 +30,8 @@ import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELIN
|
|
|
30
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,
|
|
33
|
+
import { resolveSpreadOrderSide, resolveLiveOrderLadderPosition, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, collectEdgePinnedFillIds } from './utils/order.js';
|
|
34
|
+
import { parseSlotIndex } from './utils/slot.js';
|
|
34
35
|
import { getErrorMessage, getErrorCode } from '../utils/errors.js';
|
|
35
36
|
const { toFiniteNumber } = Format;
|
|
36
37
|
function stalePlacementDropReason(action, planBoundary) {
|
|
@@ -139,7 +140,8 @@ class COWRebalanceEngine {
|
|
|
139
140
|
dustThresholdPercent,
|
|
140
141
|
gapSlots: gapSlots ?? undefined,
|
|
141
142
|
evacStreaks: evacStreaks ?? undefined,
|
|
142
|
-
assets: this.assets
|
|
143
|
+
assets: this.assets,
|
|
144
|
+
genesis: manager?._genesis ?? null
|
|
143
145
|
});
|
|
144
146
|
// Gap-evacuation telemetry: evacReady is the streak-tick output of
|
|
145
147
|
// reconcileGrid (stuck in-band candidates). It must survive both
|
|
@@ -1897,17 +1899,33 @@ class OrderManager {
|
|
|
1897
1899
|
* discriminator (null => disabled). The per-side fields are not read by the
|
|
1898
1900
|
* guard itself; they feed the book-seed cold-check and per-side seeding in
|
|
1899
1901
|
* seedLastFilledPricesFromBook.
|
|
1902
|
+
*
|
|
1903
|
+
* EDGE-PINNED FILLS ARE SKIPPED. An edge order is static fat-finger
|
|
1904
|
+
* insurance resting at the grid floor/ceiling, not market movement: the
|
|
1905
|
+
* boundary crawl already excludes its fills, and the pivot doubles as the
|
|
1906
|
+
* geometry anchor for reanchorBoundaryFromLastFill. Letting a wick on an
|
|
1907
|
+
* edge order arm the pivot at a rail-edge price would both veto that whole
|
|
1908
|
+
* side of the book and (as an absolute anchor) teleport the window to the
|
|
1909
|
+
* edge. Skipping keeps the reference on the last WINDOW trade, matching
|
|
1910
|
+
* the crawl's classification (collectEdgePinnedFillIds is the shared
|
|
1911
|
+
* definition).
|
|
1900
1912
|
* @param {Array} fills
|
|
1901
1913
|
*/
|
|
1902
1914
|
recordLastFilledPrices(fills) {
|
|
1903
1915
|
if (!Array.isArray(fills) || fills.length === 0)
|
|
1904
1916
|
return;
|
|
1917
|
+
const edgeFillIds = collectEdgePinnedFillIds(this, fills);
|
|
1905
1918
|
let recorded = 0;
|
|
1919
|
+
let skippedEdge = 0;
|
|
1906
1920
|
let lastKind = 'unknown';
|
|
1907
1921
|
let lastPriceSrc = 'direct';
|
|
1908
1922
|
for (const f of fills) {
|
|
1909
1923
|
if (!f || (f.type !== ORDER_TYPES.BUY && f.type !== ORDER_TYPES.SELL))
|
|
1910
1924
|
continue;
|
|
1925
|
+
if (f.id != null && edgeFillIds.has(String(f.id))) {
|
|
1926
|
+
skippedEdge++;
|
|
1927
|
+
continue;
|
|
1928
|
+
}
|
|
1911
1929
|
let price = Number(f.price ?? f.order?.price);
|
|
1912
1930
|
let priceSrc = 'direct';
|
|
1913
1931
|
if (!Number.isFinite(price) || price <= 0) {
|
|
@@ -1937,7 +1955,14 @@ class OrderManager {
|
|
|
1937
1955
|
const fmt = (v) => (v == null || !Number.isFinite(Number(v)) ? 'none' : Format.formatPrice6(Number(v)));
|
|
1938
1956
|
this.logger?.log?.(`[FILL-PIVOT] pivot=${fmt(this._lastFilledPrice)}(${this._lastFilledType}) ` +
|
|
1939
1957
|
`buy=${fmt(this._lastFilledBuyPrice)} sell=${fmt(this._lastFilledSellPrice)} ` +
|
|
1940
|
-
`n=${recorded} src=${lastKind}/${lastPriceSrc}
|
|
1958
|
+
`n=${recorded} src=${lastKind}/${lastPriceSrc}` +
|
|
1959
|
+
`${skippedEdge > 0 ? ` edge-skipped=${skippedEdge}` : ''}`, 'info');
|
|
1960
|
+
}
|
|
1961
|
+
catch { /* logging is best-effort */ }
|
|
1962
|
+
}
|
|
1963
|
+
else if (skippedEdge > 0) {
|
|
1964
|
+
try {
|
|
1965
|
+
this.logger?.log?.(`[FILL-PIVOT] ${skippedEdge} edge-pinned fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade`, 'info');
|
|
1941
1966
|
}
|
|
1942
1967
|
catch { /* logging is best-effort */ }
|
|
1943
1968
|
}
|
|
@@ -2143,7 +2168,8 @@ class OrderManager {
|
|
|
2143
2168
|
dustThresholdPercent: this.config?.gridLimits?.PARTIAL_DUST_THRESHOLD_PERCENTAGE,
|
|
2144
2169
|
gapSlots: this._gapSlots,
|
|
2145
2170
|
evacStreaks: this._gapEvacStreaks,
|
|
2146
|
-
assets: this.assets
|
|
2171
|
+
assets: this.assets,
|
|
2172
|
+
genesis: this._genesis ?? null
|
|
2147
2173
|
});
|
|
2148
2174
|
}
|
|
2149
2175
|
/**
|
|
@@ -2197,9 +2223,17 @@ class OrderManager {
|
|
|
2197
2223
|
const chainOrderId = candidate?.orderId;
|
|
2198
2224
|
if (!slotId || !chainOrderId)
|
|
2199
2225
|
continue;
|
|
2200
|
-
// 1.
|
|
2201
|
-
|
|
2202
|
-
|
|
2226
|
+
// 1. Live slot check + geometry re-verification against the CURRENT
|
|
2227
|
+
// committed boundary. Prefer the order's LIVE chain price: a
|
|
2228
|
+
// refused-commit adoption can leave the local slot id in-rail while
|
|
2229
|
+
// the order actually rests inside the band.
|
|
2230
|
+
const slot = this.orders.get(slotId);
|
|
2231
|
+
if (!slot || !isOrderOnChain(slot) || slot.orderId !== chainOrderId)
|
|
2232
|
+
continue;
|
|
2233
|
+
const live = resolveLiveOrderLadderPosition(slot, this.assets, this._genesis);
|
|
2234
|
+
// Unknown ladder position is not evidence of an in-band order.
|
|
2235
|
+
if (live.idx === null || !Number.isFinite(Number(live.idx))
|
|
2236
|
+
|| geometryTypeForSlotIndex(live.idx, boundary, gapSlots) !== ORDER_TYPES.SPREAD)
|
|
2203
2237
|
continue;
|
|
2204
2238
|
// 2. Act threshold (stricter than the warn threshold).
|
|
2205
2239
|
if (Number(this._gapEvacStreaks.get(slotId) || 0) < cancelThreshold)
|
|
@@ -2209,10 +2243,6 @@ class OrderManager {
|
|
|
2209
2243
|
continue;
|
|
2210
2244
|
if (this.ordersNeedingPriceCorrection.some((entry) => entry?.chainOrderId === chainOrderId))
|
|
2211
2245
|
continue;
|
|
2212
|
-
// 5. Live slot check.
|
|
2213
|
-
const slot = this.orders.get(slotId);
|
|
2214
|
-
if (!slot || !isOrderOnChain(slot) || slot.orderId !== chainOrderId)
|
|
2215
|
-
continue;
|
|
2216
2246
|
this.ordersNeedingPriceCorrection.push({
|
|
2217
2247
|
gridOrder: { ...slot },
|
|
2218
2248
|
chainOrderId,
|
|
@@ -52,7 +52,8 @@ import { isSlotInRail } from './utils/math.js';
|
|
|
52
52
|
import { deriveTargetBoundary, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, resolveEdgeCount, resolveLiveEdgeAnchorPrice, selectEdgeSlots, isShiftEligibleFill } from './utils/order.js';
|
|
53
53
|
import { reanchorBoundaryFromLastFill } from './utils/system.js';
|
|
54
54
|
import { assignGridRoles } from './utils/order.js';
|
|
55
|
-
import { convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex,
|
|
55
|
+
import { convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, hasOnChainId, isOrderPlaced } from "./utils/order.js";
|
|
56
|
+
import { parseSlotIndex } from "./utils/slot.js";
|
|
56
57
|
class StrategyEngine {
|
|
57
58
|
manager;
|
|
58
59
|
/**
|
|
@@ -271,9 +272,28 @@ class StrategyEngine {
|
|
|
271
272
|
// inventory. The fill is the anchor: place it outside its own window.
|
|
272
273
|
// Validated like a boundary commit (strands no live in-band order), and
|
|
273
274
|
// only for an on-ladder fill price.
|
|
274
|
-
const reanchor = reanchorBoundaryFromLastFill(this.manager, newBoundaryIdx, allSlots, gapSlots);
|
|
275
|
+
const reanchor = reanchorBoundaryFromLastFill(this.manager, newBoundaryIdx, allSlots, gapSlots, fills);
|
|
275
276
|
if (reanchor.reanchored) {
|
|
276
277
|
newBoundaryIdx = reanchor.boundaryIdx;
|
|
278
|
+
// An absolute fill anchor already reflects every older owed crawl.
|
|
279
|
+
// The derivation may have left records owed (cap exhausted, mixed
|
|
280
|
+
// remainder), so consuming only its subset would let a later
|
|
281
|
+
// derivation apply those deltas ON TOP of the re-anchored boundary
|
|
282
|
+
// and overshoot. Snapshot at PLAN time (not commit time): a fill
|
|
283
|
+
// recorded after this plan must stay owed and crawl next cycle.
|
|
284
|
+
const pendingAtPlan = Array.isArray(this.manager._pendingFillCrawls)
|
|
285
|
+
? this.manager._pendingFillCrawls
|
|
286
|
+
: [];
|
|
287
|
+
consumedCrawlIds = pendingAtPlan
|
|
288
|
+
.filter((e) => e && typeof e.slotId === 'string' && e.slotId.length > 0)
|
|
289
|
+
.map((e) => {
|
|
290
|
+
const ts = Number(e.ts);
|
|
291
|
+
return {
|
|
292
|
+
slotId: e.slotId,
|
|
293
|
+
side: String(e.side ?? ''),
|
|
294
|
+
...(Number.isFinite(ts) ? { ts } : {})
|
|
295
|
+
};
|
|
296
|
+
});
|
|
277
297
|
try {
|
|
278
298
|
this.manager._markGridDirty?.();
|
|
279
299
|
}
|
|
@@ -141,6 +141,16 @@ interface FillTransitionParams {
|
|
|
141
141
|
blockNum?: number;
|
|
142
142
|
historyId?: string;
|
|
143
143
|
isMaker: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Execution price (quote per base) from the chain fill / chain order, when
|
|
146
|
+
* known. The fill record must carry the REAL trade price: `matchedGridOrder`
|
|
147
|
+
* is keyed by slot, and a refused-commit adoption can leave that slot at a
|
|
148
|
+
* stale generation price (e.g. slot-118 @1267 while the chain order traded
|
|
149
|
+
* at 1345.7). The last-fill pivot / re-anchor read this field, never the
|
|
150
|
+
* slot price. The slot's own identity price is intentionally NOT rewritten
|
|
151
|
+
* (GRID-PRICE-INVARIANT).
|
|
152
|
+
*/
|
|
153
|
+
fillPrice?: number | null;
|
|
144
154
|
}
|
|
145
155
|
interface SyncChainData {
|
|
146
156
|
gridOrderId?: string;
|
|
@@ -290,7 +300,7 @@ declare class SyncEngine {
|
|
|
290
300
|
unmatchedChainOrders: UnmatchedChainOrder[];
|
|
291
301
|
}>;
|
|
292
302
|
_findMatchingGridOrder(mgr: OrderManagerLike, orderId: string | null | undefined): ManagedOrder | null;
|
|
293
|
-
_computeFillContext(mgr: OrderManagerLike, matchedGridOrder: ManagedOrder, paysAssetId: string | null | undefined, paysAmountRaw: number): {
|
|
303
|
+
_computeFillContext(mgr: OrderManagerLike, matchedGridOrder: ManagedOrder, paysAssetId: string | null | undefined, paysAmountRaw: number, receivesAssetId?: string | null | undefined, receivesAmountRaw?: number | null): {
|
|
294
304
|
orderType: OrderType;
|
|
295
305
|
currentSize: number;
|
|
296
306
|
precision: number;
|
|
@@ -298,6 +308,7 @@ declare class SyncEngine {
|
|
|
298
308
|
currentSizeIntFromGrid: number;
|
|
299
309
|
rawForSaleInt: number;
|
|
300
310
|
driftSignal: boolean;
|
|
311
|
+
fillPrice: number | null;
|
|
301
312
|
};
|
|
302
313
|
_computeFillTransitionResult(mgr: OrderManagerLike, params: FillTransitionParams): Promise<{
|
|
303
314
|
isFull: boolean;
|
|
@@ -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, 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 } 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';
|
|
@@ -468,7 +468,15 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
|
|
|
468
468
|
matchedGridOrderIds.delete(bestMatch.id);
|
|
469
469
|
return false;
|
|
470
470
|
}
|
|
471
|
-
filledOrders.push({
|
|
471
|
+
filledOrders.push({
|
|
472
|
+
...bestMatch,
|
|
473
|
+
// Pass-2 adoption of an already-gone order: the parsed chain
|
|
474
|
+
// price is the only trade fact available (bestMatch.price is
|
|
475
|
+
// the slot identity and may be stale).
|
|
476
|
+
...(Number.isFinite(Number(chainOrder.price)) && Number(chainOrder.price) > 0
|
|
477
|
+
? { price: Number(chainOrder.price) }
|
|
478
|
+
: {})
|
|
479
|
+
});
|
|
472
480
|
updatedOrders.push(spreadOrder);
|
|
473
481
|
chainOrderIdsOnGrid.add(chainOrderId);
|
|
474
482
|
try {
|
|
@@ -999,14 +1007,62 @@ class SyncEngine {
|
|
|
999
1007
|
const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
|
|
1000
1008
|
const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(chainOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent);
|
|
1001
1009
|
if (!isPriceEqual) {
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
+
// GAP-EVACUATION PRECEDENCE: classify the order's REAL
|
|
1011
|
+
// chain price against the live band before queueing a
|
|
1012
|
+
// plain price correction. An order whose live price maps
|
|
1013
|
+
// inside the gap band must be cancelled, not "corrected"
|
|
1014
|
+
// back to a stale slot price (the correction would leave
|
|
1015
|
+
// it resting inside the spread). A refused-commit
|
|
1016
|
+
// adoption can leave the local slot id in-rail while the
|
|
1017
|
+
// order actually trades in-band.
|
|
1018
|
+
let inBand = false;
|
|
1019
|
+
try {
|
|
1020
|
+
if (Array.isArray(mgr._genesis?.priceLevels) && mgr._genesis.priceLevels.length > 0) {
|
|
1021
|
+
const liveIdx = Number(slotIndexForPrice(chainOrder.price, mgr._genesis));
|
|
1022
|
+
inBand = Number.isFinite(liveIdx) && liveIdx >= 0
|
|
1023
|
+
&& geometryTypeForSlotIndex(liveIdx, mgr.boundaryIdx, mgr._gapSlots) === ORDER_TYPES.SPREAD;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
catch {
|
|
1027
|
+
inBand = false;
|
|
1028
|
+
}
|
|
1029
|
+
if (inBand) {
|
|
1030
|
+
// Drop an opposite-kind queued entry for the same
|
|
1031
|
+
// chain order so the cancel and a price update cannot
|
|
1032
|
+
// both drain.
|
|
1033
|
+
if (Array.isArray(mgr.ordersNeedingPriceCorrection)) {
|
|
1034
|
+
for (let i = mgr.ordersNeedingPriceCorrection.length - 1; i >= 0; i--) {
|
|
1035
|
+
const queued = mgr.ordersNeedingPriceCorrection[i];
|
|
1036
|
+
if (queued?.chainOrderId === gridOrder.orderId && queued.isSurplus !== true) {
|
|
1037
|
+
mgr.ordersNeedingPriceCorrection.splice(i, 1);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
queueCorrection({
|
|
1042
|
+
gridOrder: { ...gridOrder },
|
|
1043
|
+
chainOrderId: gridOrder.orderId,
|
|
1044
|
+
expectedPrice: gridOrder.price,
|
|
1045
|
+
actualPrice: chainOrder.price,
|
|
1046
|
+
size: chainOrder.size,
|
|
1047
|
+
type: chainOrder.type,
|
|
1048
|
+
isSurplus: true,
|
|
1049
|
+
gapEvacuation: true,
|
|
1050
|
+
boundaryIdx: mgr.boundaryIdx
|
|
1051
|
+
});
|
|
1052
|
+
mgr.logger?.log?.(`[SYNC] Gap-evacuation queued for ${gridOrder.orderId} (slot ${gridOrder.id}): ` +
|
|
1053
|
+
`live price ${Format.formatPrice6(Number(chainOrder.price))} maps inside the gap band ` +
|
|
1054
|
+
`(boundary ${mgr.boundaryIdx}, gap ${mgr._gapSlots}) — cancelling instead of re-pricing`, 'warn');
|
|
1055
|
+
}
|
|
1056
|
+
else {
|
|
1057
|
+
queueCorrection({
|
|
1058
|
+
gridOrder: { ...gridOrder },
|
|
1059
|
+
chainOrderId: gridOrder.orderId,
|
|
1060
|
+
expectedPrice: gridOrder.price,
|
|
1061
|
+
actualPrice: chainOrder.price,
|
|
1062
|
+
size: chainOrder.size,
|
|
1063
|
+
type: gridOrder.type
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1010
1066
|
}
|
|
1011
1067
|
}
|
|
1012
1068
|
// Chain side determines which precision applies to for_sale.
|
|
@@ -1126,7 +1182,7 @@ class SyncEngine {
|
|
|
1126
1182
|
// processing (deriveTargetBoundary) derives boundary
|
|
1127
1183
|
// movement from fill.type, and a SPREAD type would
|
|
1128
1184
|
// silently drop the shift for this completed order.
|
|
1129
|
-
filledOrders.push({ ...gridOrder, type: chainOrder.type });
|
|
1185
|
+
filledOrders.push({ ...gridOrder, type: chainOrder.type, price: toFiniteNumber(chainOrder.price, gridOrder.price) });
|
|
1130
1186
|
updatedOrders.push(spreadOrder);
|
|
1131
1187
|
}
|
|
1132
1188
|
}
|
|
@@ -1195,7 +1251,27 @@ class SyncEngine {
|
|
|
1195
1251
|
if (resolvedType === ORDER_TYPES.SPREAD) {
|
|
1196
1252
|
resolvedType = resolveSpreadOrderSide(currentGridOrder.price, mgr.config.startPrice);
|
|
1197
1253
|
}
|
|
1198
|
-
|
|
1254
|
+
const liveChainPrice = (() => {
|
|
1255
|
+
const raw = currentGridOrder?.rawOnChain;
|
|
1256
|
+
if (!raw)
|
|
1257
|
+
return null;
|
|
1258
|
+
try {
|
|
1259
|
+
const parsed = parseChainOrder(raw, mgr.assets);
|
|
1260
|
+
if (!parsed)
|
|
1261
|
+
return null;
|
|
1262
|
+
if (currentGridOrder.orderId && parsed.orderId !== currentGridOrder.orderId)
|
|
1263
|
+
return null;
|
|
1264
|
+
return Number.isFinite(Number(parsed.price)) && Number(parsed.price) > 0 ? Number(parsed.price) : null;
|
|
1265
|
+
}
|
|
1266
|
+
catch {
|
|
1267
|
+
return null;
|
|
1268
|
+
}
|
|
1269
|
+
})();
|
|
1270
|
+
filledOrders.push({
|
|
1271
|
+
...currentGridOrder,
|
|
1272
|
+
type: resolvedType,
|
|
1273
|
+
...(liveChainPrice != null ? { price: liveChainPrice } : {})
|
|
1274
|
+
});
|
|
1199
1275
|
}
|
|
1200
1276
|
}
|
|
1201
1277
|
}
|
|
@@ -1331,7 +1407,7 @@ class SyncEngine {
|
|
|
1331
1407
|
}
|
|
1332
1408
|
return null;
|
|
1333
1409
|
}
|
|
1334
|
-
_computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) {
|
|
1410
|
+
_computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId = null, receivesAmountRaw = null) {
|
|
1335
1411
|
const assets = mgr.assets;
|
|
1336
1412
|
if (!assets?.assetA || !assets?.assetB)
|
|
1337
1413
|
throw new Error('assets required for fill context');
|
|
@@ -1366,10 +1442,44 @@ class SyncEngine {
|
|
|
1366
1442
|
const rawForSale = matchedGridOrder?.rawOnChain?.for_sale;
|
|
1367
1443
|
const rawForSaleInt = rawForSale !== undefined && rawForSale !== null ? toFiniteNumber(rawForSale) : NaN;
|
|
1368
1444
|
const driftSignal = Number.isFinite(rawForSaleInt) && Math.round(rawForSaleInt) < currentSizeIntFromGrid;
|
|
1369
|
-
|
|
1445
|
+
// Execution price from the actual paid/received amounts (quote per
|
|
1446
|
+
// base). This is the fill FACT the last-fill pivot and the re-anchor
|
|
1447
|
+
// need; the slot price is only a grid identity and may be stale after
|
|
1448
|
+
// a refused-commit chain adoption.
|
|
1449
|
+
let fillPrice = null;
|
|
1450
|
+
if (Number.isFinite(Number(receivesAmountRaw)) && Number(receivesAmountRaw) > 0
|
|
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
|
+
}
|
|
1474
|
+
return { orderType, currentSize, precision, filledAmount, currentSizeIntFromGrid, rawForSaleInt, driftSignal, fillPrice };
|
|
1370
1475
|
}
|
|
1371
1476
|
async _computeFillTransitionResult(mgr, params) {
|
|
1372
|
-
const { matchedGridOrder, orderType, precision, filledAmount, filledAmountInt, currentSizeIntFromGrid, chainRefetched, chainConfirmsEmpty, effectiveRawForSale, blockNum, historyId, isMaker } = params;
|
|
1477
|
+
const { matchedGridOrder, orderType, precision, filledAmount, filledAmountInt, currentSizeIntFromGrid, chainRefetched, chainConfirmsEmpty, effectiveRawForSale, blockNum, historyId, isMaker, fillPrice } = params;
|
|
1478
|
+
// Fill price provenance: prefer the real execution price, fall back to
|
|
1479
|
+
// the slot level only when no chain price/amounts are available.
|
|
1480
|
+
const resolvedFillPrice = Number.isFinite(Number(fillPrice)) && Number(fillPrice) > 0
|
|
1481
|
+
? Number(fillPrice)
|
|
1482
|
+
: matchedGridOrder.price;
|
|
1373
1483
|
let resolvedChainConfirmsEmpty = chainConfirmsEmpty;
|
|
1374
1484
|
if (chainRefetched && Number.isFinite(effectiveRawForSale) && Math.round(effectiveRawForSale) <= 0) {
|
|
1375
1485
|
resolvedChainConfirmsEmpty = true;
|
|
@@ -1462,6 +1572,7 @@ class SyncEngine {
|
|
|
1462
1572
|
filledOrderResult = {
|
|
1463
1573
|
...matchedGridOrder,
|
|
1464
1574
|
type: orderType,
|
|
1575
|
+
price: resolvedFillPrice,
|
|
1465
1576
|
blockNum,
|
|
1466
1577
|
historyId,
|
|
1467
1578
|
isMaker
|
|
@@ -1471,6 +1582,7 @@ class SyncEngine {
|
|
|
1471
1582
|
filledOrderResult = {
|
|
1472
1583
|
...matchedGridOrder,
|
|
1473
1584
|
type: orderType,
|
|
1585
|
+
price: resolvedFillPrice,
|
|
1474
1586
|
size: filledAmount,
|
|
1475
1587
|
isPartial: true,
|
|
1476
1588
|
blockNum,
|
|
@@ -1573,7 +1685,7 @@ class SyncEngine {
|
|
|
1573
1685
|
mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
|
|
1574
1686
|
return { filledOrders: [], updatedOrders: [], partialFill: false };
|
|
1575
1687
|
}
|
|
1576
|
-
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw);
|
|
1688
|
+
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
|
|
1577
1689
|
mgr.logger.log(`[SYNC] Order ${orderId} (${ctx.orderType}) currentSize=${ctx.currentSize}, filledAmount=${ctx.filledAmount}`, 'debug');
|
|
1578
1690
|
let effectiveRawForSale = ctx.rawForSaleInt;
|
|
1579
1691
|
let chainConfirmsEmpty = false;
|
|
@@ -1612,7 +1724,8 @@ class SyncEngine {
|
|
|
1612
1724
|
effectiveRawForSale,
|
|
1613
1725
|
blockNum,
|
|
1614
1726
|
historyId,
|
|
1615
|
-
isMaker
|
|
1727
|
+
isMaker,
|
|
1728
|
+
fillPrice: ctx.fillPrice
|
|
1616
1729
|
});
|
|
1617
1730
|
const filledOrders = [];
|
|
1618
1731
|
const updatedOrders = [];
|
|
@@ -1772,7 +1885,7 @@ class SyncEngine {
|
|
|
1772
1885
|
anyRequiresSync = true;
|
|
1773
1886
|
continue;
|
|
1774
1887
|
}
|
|
1775
|
-
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw);
|
|
1888
|
+
const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, entry.receivesAssetId, entry.receivesAmountRaw);
|
|
1776
1889
|
mgr.logger.log(`[SYNC] Order ${orderId} (${ctx.orderType}) currentSize=${ctx.currentSize}, filledAmount=${ctx.filledAmount}`, 'debug');
|
|
1777
1890
|
if (ctx.driftSignal && orderId) {
|
|
1778
1891
|
driftOrderIds.add(orderId);
|
|
@@ -1784,7 +1897,8 @@ class SyncEngine {
|
|
|
1784
1897
|
filledAmount: ctx.filledAmount,
|
|
1785
1898
|
filledAmountInt: floatToBlockchainInt(ctx.filledAmount, ctx.precision),
|
|
1786
1899
|
currentSizeIntFromGrid: ctx.currentSizeIntFromGrid,
|
|
1787
|
-
rawForSaleInt: ctx.rawForSaleInt
|
|
1900
|
+
rawForSaleInt: ctx.rawForSaleInt,
|
|
1901
|
+
fillPrice: ctx.fillPrice
|
|
1788
1902
|
});
|
|
1789
1903
|
}
|
|
1790
1904
|
// Phase 5: Batch drift refetch — one get_objects call for all order IDs
|
|
@@ -1886,7 +2000,8 @@ class SyncEngine {
|
|
|
1886
2000
|
effectiveRawForSale,
|
|
1887
2001
|
blockNum: lastCtx.entry.blockNum,
|
|
1888
2002
|
historyId: lastCtx.entry.historyId,
|
|
1889
|
-
isMaker: lastCtx.entry.isMaker
|
|
2003
|
+
isMaker: lastCtx.entry.isMaker,
|
|
2004
|
+
fillPrice: lastCtx.fillPrice
|
|
1890
2005
|
});
|
|
1891
2006
|
if (result.isFull) {
|
|
1892
2007
|
mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
|
|
@@ -838,11 +838,10 @@ declare function validateOrderSize(orderSize: number, orderType: string, assets:
|
|
|
838
838
|
* @param {number} weight - Weight factor (0-1) controlling distribution steepness
|
|
839
839
|
* @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
|
|
840
840
|
* @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
|
|
841
|
-
* @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
|
|
842
841
|
* @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
|
|
843
842
|
* @returns {Array<number>} Array of n allocation sizes
|
|
844
843
|
*/
|
|
845
|
-
declare function allocateFundsByWeights(totalFunds: number, n: number, weight: unknown, incrementFactor: number, reverse?: boolean,
|
|
844
|
+
declare function allocateFundsByWeights(totalFunds: number, n: number, weight: unknown, incrementFactor: number, reverse?: boolean, precision?: number | null): number[];
|
|
846
845
|
/**
|
|
847
846
|
* Calculate order sizes for a list of orders using weighted fund allocation.
|
|
848
847
|
* Allocates buy and sell funds separately using weight distribution from config.
|
|
@@ -852,13 +851,11 @@ declare function allocateFundsByWeights(totalFunds: number, n: number, weight: u
|
|
|
852
851
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
853
852
|
* @param {number} sellFunds - Total funds available for SELL orders
|
|
854
853
|
* @param {number} buyFunds - Total funds available for BUY orders
|
|
855
|
-
* @param {number} [minSellSize=0] - Minimum size for sell allocations
|
|
856
|
-
* @param {number} [minBuySize=0] - Minimum size for buy allocations
|
|
857
854
|
* @param {number} [precisionA=null] - Precision for assetA (SELL asset)
|
|
858
855
|
* @param {number} [precisionB=null] - Precision for assetB (BUY asset)
|
|
859
856
|
* @returns {Array<Object>} Orders array with size property added to each
|
|
860
857
|
*/
|
|
861
|
-
declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig, sellFunds: number, buyFunds: number,
|
|
858
|
+
declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig, sellFunds: number, buyFunds: number, precisionA?: number | null, precisionB?: number | null): ManagedOrder[];
|
|
862
859
|
/**
|
|
863
860
|
* Calculate order sizes for rotation operations.
|
|
864
861
|
* Combines available funds with existing grid allocation for sizing.
|
|
@@ -869,11 +866,10 @@ declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig,
|
|
|
869
866
|
* @param {number} orderCount - Number of orders to size
|
|
870
867
|
* @param {string} orderType - Order type (BUY or SELL)
|
|
871
868
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
872
|
-
* @param {number} [minSize=0] - Minimum size for each allocation
|
|
873
869
|
* @param {number} [precision=null] - Asset precision for quantization
|
|
874
870
|
* @returns {Array<number>} Array of order sizes
|
|
875
871
|
*/
|
|
876
|
-
declare function calculateRotationOrderSizes(availableFunds: number, totalGridAllocation: number, orderCount: number, orderType: string, config: GridConfig,
|
|
872
|
+
declare function calculateRotationOrderSizes(availableFunds: number, totalGridAllocation: number, orderCount: number, orderType: string, config: GridConfig, precision?: number | null): number[];
|
|
877
873
|
/**
|
|
878
874
|
* Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
|
|
879
875
|
* Measures how much the current grid differs from the calculated ideal.
|
|
@@ -894,7 +890,7 @@ declare function calculateGridSideDivergenceMetric(calculatedOrders: ManagedOrde
|
|
|
894
890
|
* Works for all pairs — returns the BTS fee budget needed for order operations.
|
|
895
891
|
*
|
|
896
892
|
* @param {string} assetA - First asset symbol
|
|
897
|
-
* @param {string} assetB - Second asset symbol (
|
|
893
|
+
* @param {string} assetB - Second asset symbol (used only to label the fee-cache warning)
|
|
898
894
|
* @param {number} totalOrders - Number of orders to create
|
|
899
895
|
* @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
|
|
900
896
|
* @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
|
|
@@ -1025,6 +1021,7 @@ declare const BOUNDARY_REJECT_PLACED_IN_BAND = "placed_order_in_band";
|
|
|
1025
1021
|
*/
|
|
1026
1022
|
declare function validateBoundaryCommit(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
|
|
1027
1023
|
rejectInBandPlacements?: boolean;
|
|
1024
|
+
allowInBandSlotIds?: Iterable<string>;
|
|
1028
1025
|
}): {
|
|
1029
1026
|
ok: boolean;
|
|
1030
1027
|
reason?: string;
|
|
@@ -1058,7 +1055,9 @@ declare function validateBoundaryCommit(proposedBoundary: number | null | undefi
|
|
|
1058
1055
|
* in-progress evacuation; true poison still refuses and structural resync
|
|
1059
1056
|
* falls through to the clean full-grid reset instead of re-ingesting damage.
|
|
1060
1057
|
*/
|
|
1061
|
-
declare function validatePersistedBoundary(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number
|
|
1058
|
+
declare function validatePersistedBoundary(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
|
|
1059
|
+
allowInBandSlotIds?: Iterable<string>;
|
|
1060
|
+
}): {
|
|
1062
1061
|
ok: boolean;
|
|
1063
1062
|
reason?: string;
|
|
1064
1063
|
detail?: string;
|
|
@@ -1226,11 +1226,10 @@ function validateOrderSize(orderSize, orderType, assets, minFactor = GRID_LIMITS
|
|
|
1226
1226
|
* @param {number} weight - Weight factor (0-1) controlling distribution steepness
|
|
1227
1227
|
* @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
|
|
1228
1228
|
* @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
|
|
1229
|
-
* @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
|
|
1230
1229
|
* @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
|
|
1231
1230
|
* @returns {Array<number>} Array of n allocation sizes
|
|
1232
1231
|
*/
|
|
1233
|
-
function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false,
|
|
1232
|
+
function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false, precision = null) {
|
|
1234
1233
|
if (n <= 0)
|
|
1235
1234
|
return [];
|
|
1236
1235
|
if (!Number.isFinite(totalFunds) || totalFunds <= 0)
|
|
@@ -1282,21 +1281,19 @@ function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse
|
|
|
1282
1281
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
1283
1282
|
* @param {number} sellFunds - Total funds available for SELL orders
|
|
1284
1283
|
* @param {number} buyFunds - Total funds available for BUY orders
|
|
1285
|
-
* @param {number} [minSellSize=0] - Minimum size for sell allocations
|
|
1286
|
-
* @param {number} [minBuySize=0] - Minimum size for buy allocations
|
|
1287
1284
|
* @param {number} [precisionA=null] - Precision for assetA (SELL asset)
|
|
1288
1285
|
* @param {number} [precisionB=null] - Precision for assetB (BUY asset)
|
|
1289
1286
|
* @returns {Array<Object>} Orders array with size property added to each
|
|
1290
1287
|
*/
|
|
1291
|
-
function calculateOrderSizes(orders, config, sellFunds, buyFunds,
|
|
1288
|
+
function calculateOrderSizes(orders, config, sellFunds, buyFunds, precisionA = null, precisionB = null) {
|
|
1292
1289
|
const incrementPercent = config.incrementPercent ?? 0;
|
|
1293
1290
|
const sellWeight = config.weightDistribution?.sell ?? 0;
|
|
1294
1291
|
const buyWeight = config.weightDistribution?.buy ?? 0;
|
|
1295
1292
|
const incrementFactor = incrementPercent / 100;
|
|
1296
1293
|
const sellOrders = orders.filter((o) => o.type === ORDER_TYPES.SELL);
|
|
1297
1294
|
const buyOrders = orders.filter((o) => o.type === ORDER_TYPES.BUY);
|
|
1298
|
-
const sellSizes = allocateFundsByWeights(sellFunds, sellOrders.length, sellWeight, incrementFactor, false,
|
|
1299
|
-
const buySizes = allocateFundsByWeights(buyFunds, buyOrders.length, buyWeight, incrementFactor, true,
|
|
1295
|
+
const sellSizes = allocateFundsByWeights(sellFunds, sellOrders.length, sellWeight, incrementFactor, false, precisionA);
|
|
1296
|
+
const buySizes = allocateFundsByWeights(buyFunds, buyOrders.length, buyWeight, incrementFactor, true, precisionB);
|
|
1300
1297
|
const sellState = { sizes: sellSizes, index: 0 };
|
|
1301
1298
|
const buyState = { sizes: buySizes, index: 0 };
|
|
1302
1299
|
return orders.map((order) => {
|
|
@@ -1324,11 +1321,10 @@ function calculateOrderSizes(orders, config, sellFunds, buyFunds, minSellSize =
|
|
|
1324
1321
|
* @param {number} orderCount - Number of orders to size
|
|
1325
1322
|
* @param {string} orderType - Order type (BUY or SELL)
|
|
1326
1323
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
1327
|
-
* @param {number} [minSize=0] - Minimum size for each allocation
|
|
1328
1324
|
* @param {number} [precision=null] - Asset precision for quantization
|
|
1329
1325
|
* @returns {Array<number>} Array of order sizes
|
|
1330
1326
|
*/
|
|
1331
|
-
function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config,
|
|
1327
|
+
function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config, precision = null) {
|
|
1332
1328
|
if (orderCount <= 0)
|
|
1333
1329
|
return [];
|
|
1334
1330
|
const totalFunds = availableFunds + totalGridAllocation;
|
|
@@ -1339,7 +1335,7 @@ function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderC
|
|
|
1339
1335
|
const incrementFactor = incrementPercent / 100;
|
|
1340
1336
|
const weight = (orderType === ORDER_TYPES.SELL) ? (weightDistribution.sell ?? 0) : (weightDistribution.buy ?? 0);
|
|
1341
1337
|
const reverse = (orderType === ORDER_TYPES.BUY);
|
|
1342
|
-
return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse,
|
|
1338
|
+
return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse, precision);
|
|
1343
1339
|
}
|
|
1344
1340
|
/**
|
|
1345
1341
|
* Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
|
|
@@ -1404,7 +1400,7 @@ function calculateGridSideDivergenceMetric(calculatedOrders, persistedOrders, _s
|
|
|
1404
1400
|
* Works for all pairs — returns the BTS fee budget needed for order operations.
|
|
1405
1401
|
*
|
|
1406
1402
|
* @param {string} assetA - First asset symbol
|
|
1407
|
-
* @param {string} assetB - Second asset symbol (
|
|
1403
|
+
* @param {string} assetB - Second asset symbol (used only to label the fee-cache warning)
|
|
1408
1404
|
* @param {number} totalOrders - Number of orders to create
|
|
1409
1405
|
* @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
|
|
1410
1406
|
* @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
|
|
@@ -1646,6 +1642,15 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
|
|
|
1646
1642
|
let inBandCount = 0;
|
|
1647
1643
|
let firstInBandIdx = null;
|
|
1648
1644
|
let firstInBandPrice = null;
|
|
1645
|
+
// Explicit allow-list for the fill's OWN residual order (partial fill at
|
|
1646
|
+
// the anchor slot). A re-anchor to `fillSlot - gapSlots` necessarily puts
|
|
1647
|
+
// that residual inside the implied band; refusing it deadlocks the
|
|
1648
|
+
// geometry (the residual cannot be cancelled by the re-anchor itself).
|
|
1649
|
+
// Callers must pass only the last-fill residual id — ACTIVE/foreign
|
|
1650
|
+
// in-band placements stay rejected.
|
|
1651
|
+
const allowedInBand = options.allowInBandSlotIds
|
|
1652
|
+
? new Set(Array.from(options.allowInBandSlotIds).filter((id) => typeof id === 'string' && id.length > 0))
|
|
1653
|
+
: null;
|
|
1649
1654
|
for (let idx = 0; idx < sorted.length; idx++) {
|
|
1650
1655
|
const o = sorted[idx];
|
|
1651
1656
|
if (!o.orderId)
|
|
@@ -1660,6 +1665,9 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
|
|
|
1660
1665
|
minSellPrice = price;
|
|
1661
1666
|
}
|
|
1662
1667
|
else if (options.rejectInBandPlacements) {
|
|
1668
|
+
const slotId = o.id;
|
|
1669
|
+
if (allowedInBand && typeof slotId === 'string' && allowedInBand.has(slotId))
|
|
1670
|
+
continue;
|
|
1663
1671
|
inBandCount++;
|
|
1664
1672
|
if (firstInBandIdx === null) {
|
|
1665
1673
|
firstInBandIdx = idx;
|
|
@@ -1712,8 +1720,11 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
|
|
|
1712
1720
|
* in-progress evacuation; true poison still refuses and structural resync
|
|
1713
1721
|
* falls through to the clean full-grid reset instead of re-ingesting damage.
|
|
1714
1722
|
*/
|
|
1715
|
-
function validatePersistedBoundary(proposedBoundary, orders, gapSlots) {
|
|
1716
|
-
return validateBoundaryCommit(proposedBoundary, orders, gapSlots, {
|
|
1723
|
+
function validatePersistedBoundary(proposedBoundary, orders, gapSlots, options = {}) {
|
|
1724
|
+
return validateBoundaryCommit(proposedBoundary, orders, gapSlots, {
|
|
1725
|
+
rejectInBandPlacements: true,
|
|
1726
|
+
...(options.allowInBandSlotIds ? { allowInBandSlotIds: options.allowInBandSlotIds } : {})
|
|
1727
|
+
});
|
|
1717
1728
|
}
|
|
1718
1729
|
/**
|
|
1719
1730
|
* Whether a persisted-boundary rejection is the TRANSIENT kind that must not
|