dexbot 1.6.16 → 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 +58 -0
- package/analysis/README.md +10 -9
- package/analysis/ama_fitting/README.md +2 -2
- package/analysis/bot_fitting/README.md +3 -3
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -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/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
- 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/grid_reset_sim.js +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
- 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/account_bots.d.ts +3 -0
- package/dist/modules/bots_file_lock.d.ts +2 -2
- package/dist/modules/bots_file_lock.js +2 -2
- package/dist/modules/chain_keys.d.ts +1 -1
- package/dist/modules/constants.d.ts +6 -0
- package/dist/modules/constants.js +37 -6
- package/dist/modules/credit_pricing.d.ts +20 -1
- package/dist/modules/credit_pricing.js +23 -1
- package/dist/modules/credit_runtime.js +33 -16
- package/dist/modules/dexbot_class.d.ts +11 -1
- package/dist/modules/dexbot_class.js +15 -2
- package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
- package/dist/modules/dexbot_cow_runtime.js +507 -108
- package/dist/modules/dexbot_credential_client.d.ts +5 -0
- package/dist/modules/dexbot_maintenance_runtime.js +117 -12
- 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/credential_daemon.d.ts +14 -2
- package/dist/modules/launcher/credential_daemon.js +60 -26
- 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 +26 -14
- package/dist/modules/order/grid.js +416 -73
- 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 +22 -1
- package/dist/modules/order/manager.d.ts +40 -7
- package/dist/modules/order/manager.js +149 -23
- package/dist/modules/order/strategy.d.ts +5 -0
- package/dist/modules/order/strategy.js +44 -3
- 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 +49 -10
- package/dist/modules/order/utils/math.js +71 -14
- package/dist/modules/order/utils/order.d.ts +65 -11
- package/dist/modules/order/utils/order.js +198 -28
- package/dist/modules/order/utils/system.d.ts +112 -2
- package/dist/modules/order/utils/system.js +338 -12
- package/dist/modules/order/utils/validate.d.ts +4 -1
- package/dist/modules/order/utils/validate.js +9 -2
- package/dist/modules/storage/index.d.ts +3 -2
- package/dist/modules/storage/index.js +3 -2
- package/dist/modules/types.d.ts +44 -2
- package/dist/scripts/analyze-credit.js +64 -23
- package/dist/scripts/bts_distribution.d.ts +66 -0
- package/dist/scripts/bts_distribution.js +2102 -0
- package/dist/scripts/token_distribution.d.ts +45 -0
- package/dist/scripts/token_distribution.js +1870 -0
- package/dist/unlock.js +42 -24
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +24 -8
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
- package/docs/GRID_PRICE_INVARIANT.md +29 -3
- package/docs/GRID_RECALCULATION.md +3 -3
- package/docs/GRID_RECONCILE.md +5 -5
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +22 -0
- package/docs/MPA_CREDIT_USAGE.md +3 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
- package/docs/README.md +1 -1
- package/docs/architecture.md +205 -6
- package/docs/developer_guide.md +12 -0
- package/market_adapter/README.md +11 -6
- package/modules/README.md +18 -14
- package/package.json +6 -3
- package/scripts/README.md +85 -148
|
@@ -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');
|
|
@@ -442,6 +442,46 @@ declare function getAssetFeesSafe(assetSymbol: string, assetAmount?: number | nu
|
|
|
442
442
|
feeAmount?: undefined;
|
|
443
443
|
feePercent?: undefined;
|
|
444
444
|
} | null;
|
|
445
|
+
/**
|
|
446
|
+
* Fund budget for placing a KNOWN set of pending slots (spread correction).
|
|
447
|
+
*
|
|
448
|
+
* `calculateAvailableFundsValue` computes `chainFree - virtual - fees`, where
|
|
449
|
+
* `virtual` is the projection of the side's not-yet-placed (VIRTUAL) slots.
|
|
450
|
+
* That is the right number for "how much room is left beyond the projected
|
|
451
|
+
* rail", but it is CIRCULAR when the caller is funding exactly those projected
|
|
452
|
+
* slots: if the projection is larger than the account holds free (a rail sized
|
|
453
|
+
* from a bigger balance, from inventory locked in resting orders, or from
|
|
454
|
+
* optimistic proceeds), `available` reads 0 while the chain clearly holds free
|
|
455
|
+
* funds, and the projection can never shrink because nothing gets placed.
|
|
456
|
+
* Live symptom: `planned 3, placing 0` every cycle for 84 minutes
|
|
457
|
+
* (`free 454560.80` vs `virtual 456046.21`).
|
|
458
|
+
*
|
|
459
|
+
* So for a known candidate set, re-derive the budget from chain truth: add the
|
|
460
|
+
* projection back, but never more than the candidates themselves need and never
|
|
461
|
+
* more than the chain actually holds free. The chain remains the final arbiter
|
|
462
|
+
* (an over-commit is rejected at broadcast), and the fee reservation stays
|
|
463
|
+
* inside `availableFund` for every healthy cycle.
|
|
464
|
+
*
|
|
465
|
+
* Only an OVERSUBSCRIPTION (projection > chain free) triggers the fallback. A
|
|
466
|
+
* zero caused by the fee reservation or by a genuinely empty balance is a real
|
|
467
|
+
* constraint: the projection fits, so honour it (and its fees) and place
|
|
468
|
+
* nothing.
|
|
469
|
+
*
|
|
470
|
+
* @param {{availableFund?: number, virtualIntent?: number, chainFree?: number, candidateIdeals?: number}} args
|
|
471
|
+
* @returns {{budget: number, oversubscribed: number, eroded: boolean}} budget to
|
|
472
|
+
* place with; projection excess over chain free (0 = healthy); whether the
|
|
473
|
+
* chain-truth re-derivation was needed
|
|
474
|
+
*/
|
|
475
|
+
declare function deriveChainTruthFundBudget(args: {
|
|
476
|
+
availableFund?: number;
|
|
477
|
+
virtualIntent?: number;
|
|
478
|
+
chainFree?: number;
|
|
479
|
+
candidateIdeals?: number;
|
|
480
|
+
} | null | undefined): {
|
|
481
|
+
budget: number;
|
|
482
|
+
oversubscribed: number;
|
|
483
|
+
eroded: boolean;
|
|
484
|
+
};
|
|
445
485
|
/**
|
|
446
486
|
* Calculate available funds for a specific side (buy or sell).
|
|
447
487
|
* Deducts virtual reservations, BTS fees owed, and BTS fee reservation from chain-free balance.
|
|
@@ -798,11 +838,10 @@ declare function validateOrderSize(orderSize: number, orderType: string, assets:
|
|
|
798
838
|
* @param {number} weight - Weight factor (0-1) controlling distribution steepness
|
|
799
839
|
* @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
|
|
800
840
|
* @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
|
|
801
|
-
* @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
|
|
802
841
|
* @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
|
|
803
842
|
* @returns {Array<number>} Array of n allocation sizes
|
|
804
843
|
*/
|
|
805
|
-
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[];
|
|
806
845
|
/**
|
|
807
846
|
* Calculate order sizes for a list of orders using weighted fund allocation.
|
|
808
847
|
* Allocates buy and sell funds separately using weight distribution from config.
|
|
@@ -812,13 +851,11 @@ declare function allocateFundsByWeights(totalFunds: number, n: number, weight: u
|
|
|
812
851
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
813
852
|
* @param {number} sellFunds - Total funds available for SELL orders
|
|
814
853
|
* @param {number} buyFunds - Total funds available for BUY orders
|
|
815
|
-
* @param {number} [minSellSize=0] - Minimum size for sell allocations
|
|
816
|
-
* @param {number} [minBuySize=0] - Minimum size for buy allocations
|
|
817
854
|
* @param {number} [precisionA=null] - Precision for assetA (SELL asset)
|
|
818
855
|
* @param {number} [precisionB=null] - Precision for assetB (BUY asset)
|
|
819
856
|
* @returns {Array<Object>} Orders array with size property added to each
|
|
820
857
|
*/
|
|
821
|
-
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[];
|
|
822
859
|
/**
|
|
823
860
|
* Calculate order sizes for rotation operations.
|
|
824
861
|
* Combines available funds with existing grid allocation for sizing.
|
|
@@ -829,11 +866,10 @@ declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig,
|
|
|
829
866
|
* @param {number} orderCount - Number of orders to size
|
|
830
867
|
* @param {string} orderType - Order type (BUY or SELL)
|
|
831
868
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
832
|
-
* @param {number} [minSize=0] - Minimum size for each allocation
|
|
833
869
|
* @param {number} [precision=null] - Asset precision for quantization
|
|
834
870
|
* @returns {Array<number>} Array of order sizes
|
|
835
871
|
*/
|
|
836
|
-
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[];
|
|
837
873
|
/**
|
|
838
874
|
* Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
|
|
839
875
|
* Measures how much the current grid differs from the calculated ideal.
|
|
@@ -854,7 +890,7 @@ declare function calculateGridSideDivergenceMetric(calculatedOrders: ManagedOrde
|
|
|
854
890
|
* Works for all pairs — returns the BTS fee budget needed for order operations.
|
|
855
891
|
*
|
|
856
892
|
* @param {string} assetA - First asset symbol
|
|
857
|
-
* @param {string} assetB - Second asset symbol (
|
|
893
|
+
* @param {string} assetB - Second asset symbol (used only to label the fee-cache warning)
|
|
858
894
|
* @param {number} totalOrders - Number of orders to create
|
|
859
895
|
* @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
|
|
860
896
|
* @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
|
|
@@ -985,6 +1021,7 @@ declare const BOUNDARY_REJECT_PLACED_IN_BAND = "placed_order_in_band";
|
|
|
985
1021
|
*/
|
|
986
1022
|
declare function validateBoundaryCommit(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
|
|
987
1023
|
rejectInBandPlacements?: boolean;
|
|
1024
|
+
allowInBandSlotIds?: Iterable<string>;
|
|
988
1025
|
}): {
|
|
989
1026
|
ok: boolean;
|
|
990
1027
|
reason?: string;
|
|
@@ -1018,7 +1055,9 @@ declare function validateBoundaryCommit(proposedBoundary: number | null | undefi
|
|
|
1018
1055
|
* in-progress evacuation; true poison still refuses and structural resync
|
|
1019
1056
|
* falls through to the clean full-grid reset instead of re-ingesting damage.
|
|
1020
1057
|
*/
|
|
1021
|
-
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
|
+
}): {
|
|
1022
1061
|
ok: boolean;
|
|
1023
1062
|
reason?: string;
|
|
1024
1063
|
detail?: string;
|
|
@@ -1216,7 +1255,7 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
|
|
|
1216
1255
|
declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
|
|
1217
1256
|
declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
|
|
1218
1257
|
export type { FeeCacheEntry };
|
|
1219
|
-
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, 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 };
|
|
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 };
|
|
1220
1259
|
/**
|
|
1221
1260
|
* Round a value to a given factor.
|
|
1222
1261
|
* @param {number} value - Value to round
|
|
@@ -458,6 +458,52 @@ function getAssetFeesSafe(assetSymbol, assetAmount = null, isMaker = true) {
|
|
|
458
458
|
return null;
|
|
459
459
|
}
|
|
460
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* Fund budget for placing a KNOWN set of pending slots (spread correction).
|
|
463
|
+
*
|
|
464
|
+
* `calculateAvailableFundsValue` computes `chainFree - virtual - fees`, where
|
|
465
|
+
* `virtual` is the projection of the side's not-yet-placed (VIRTUAL) slots.
|
|
466
|
+
* That is the right number for "how much room is left beyond the projected
|
|
467
|
+
* rail", but it is CIRCULAR when the caller is funding exactly those projected
|
|
468
|
+
* slots: if the projection is larger than the account holds free (a rail sized
|
|
469
|
+
* from a bigger balance, from inventory locked in resting orders, or from
|
|
470
|
+
* optimistic proceeds), `available` reads 0 while the chain clearly holds free
|
|
471
|
+
* funds, and the projection can never shrink because nothing gets placed.
|
|
472
|
+
* Live symptom: `planned 3, placing 0` every cycle for 84 minutes
|
|
473
|
+
* (`free 454560.80` vs `virtual 456046.21`).
|
|
474
|
+
*
|
|
475
|
+
* So for a known candidate set, re-derive the budget from chain truth: add the
|
|
476
|
+
* projection back, but never more than the candidates themselves need and never
|
|
477
|
+
* more than the chain actually holds free. The chain remains the final arbiter
|
|
478
|
+
* (an over-commit is rejected at broadcast), and the fee reservation stays
|
|
479
|
+
* inside `availableFund` for every healthy cycle.
|
|
480
|
+
*
|
|
481
|
+
* Only an OVERSUBSCRIPTION (projection > chain free) triggers the fallback. A
|
|
482
|
+
* zero caused by the fee reservation or by a genuinely empty balance is a real
|
|
483
|
+
* constraint: the projection fits, so honour it (and its fees) and place
|
|
484
|
+
* nothing.
|
|
485
|
+
*
|
|
486
|
+
* @param {{availableFund?: number, virtualIntent?: number, chainFree?: number, candidateIdeals?: number}} args
|
|
487
|
+
* @returns {{budget: number, oversubscribed: number, eroded: boolean}} budget to
|
|
488
|
+
* place with; projection excess over chain free (0 = healthy); whether the
|
|
489
|
+
* chain-truth re-derivation was needed
|
|
490
|
+
*/
|
|
491
|
+
function deriveChainTruthFundBudget(args) {
|
|
492
|
+
const available = Math.max(0, toFiniteNumber(args?.availableFund, 0));
|
|
493
|
+
const virtual = Math.max(0, toFiniteNumber(args?.virtualIntent, 0));
|
|
494
|
+
const chainFree = Math.max(0, toFiniteNumber(args?.chainFree, 0));
|
|
495
|
+
const ideals = Math.max(0, toFiniteNumber(args?.candidateIdeals, 0));
|
|
496
|
+
const oversubscribed = Math.max(0, virtual - chainFree);
|
|
497
|
+
// `oversubscribed <= 0` means the projection FITS in the free balance, so a
|
|
498
|
+
// zero `available` is a real constraint (fees/reservation), not the circular
|
|
499
|
+
// case — never re-derive past it.
|
|
500
|
+
if (available > 0 || oversubscribed <= 0 || ideals <= 0 || chainFree <= 0) {
|
|
501
|
+
return { budget: available, oversubscribed, eroded: false };
|
|
502
|
+
}
|
|
503
|
+
// Oversubscribed: fund the candidates from what the chain really holds.
|
|
504
|
+
const budget = Math.min(chainFree, Math.min(virtual, ideals));
|
|
505
|
+
return { budget, oversubscribed, eroded: budget > 0 };
|
|
506
|
+
}
|
|
461
507
|
/**
|
|
462
508
|
* Calculate available funds for a specific side (buy or sell).
|
|
463
509
|
* Deducts virtual reservations, BTS fees owed, and BTS fee reservation from chain-free balance.
|
|
@@ -1180,11 +1226,10 @@ function validateOrderSize(orderSize, orderType, assets, minFactor = GRID_LIMITS
|
|
|
1180
1226
|
* @param {number} weight - Weight factor (0-1) controlling distribution steepness
|
|
1181
1227
|
* @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
|
|
1182
1228
|
* @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
|
|
1183
|
-
* @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
|
|
1184
1229
|
* @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
|
|
1185
1230
|
* @returns {Array<number>} Array of n allocation sizes
|
|
1186
1231
|
*/
|
|
1187
|
-
function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false,
|
|
1232
|
+
function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false, precision = null) {
|
|
1188
1233
|
if (n <= 0)
|
|
1189
1234
|
return [];
|
|
1190
1235
|
if (!Number.isFinite(totalFunds) || totalFunds <= 0)
|
|
@@ -1236,21 +1281,19 @@ function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse
|
|
|
1236
1281
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
1237
1282
|
* @param {number} sellFunds - Total funds available for SELL orders
|
|
1238
1283
|
* @param {number} buyFunds - Total funds available for BUY orders
|
|
1239
|
-
* @param {number} [minSellSize=0] - Minimum size for sell allocations
|
|
1240
|
-
* @param {number} [minBuySize=0] - Minimum size for buy allocations
|
|
1241
1284
|
* @param {number} [precisionA=null] - Precision for assetA (SELL asset)
|
|
1242
1285
|
* @param {number} [precisionB=null] - Precision for assetB (BUY asset)
|
|
1243
1286
|
* @returns {Array<Object>} Orders array with size property added to each
|
|
1244
1287
|
*/
|
|
1245
|
-
function calculateOrderSizes(orders, config, sellFunds, buyFunds,
|
|
1288
|
+
function calculateOrderSizes(orders, config, sellFunds, buyFunds, precisionA = null, precisionB = null) {
|
|
1246
1289
|
const incrementPercent = config.incrementPercent ?? 0;
|
|
1247
1290
|
const sellWeight = config.weightDistribution?.sell ?? 0;
|
|
1248
1291
|
const buyWeight = config.weightDistribution?.buy ?? 0;
|
|
1249
1292
|
const incrementFactor = incrementPercent / 100;
|
|
1250
1293
|
const sellOrders = orders.filter((o) => o.type === ORDER_TYPES.SELL);
|
|
1251
1294
|
const buyOrders = orders.filter((o) => o.type === ORDER_TYPES.BUY);
|
|
1252
|
-
const sellSizes = allocateFundsByWeights(sellFunds, sellOrders.length, sellWeight, incrementFactor, false,
|
|
1253
|
-
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);
|
|
1254
1297
|
const sellState = { sizes: sellSizes, index: 0 };
|
|
1255
1298
|
const buyState = { sizes: buySizes, index: 0 };
|
|
1256
1299
|
return orders.map((order) => {
|
|
@@ -1278,11 +1321,10 @@ function calculateOrderSizes(orders, config, sellFunds, buyFunds, minSellSize =
|
|
|
1278
1321
|
* @param {number} orderCount - Number of orders to size
|
|
1279
1322
|
* @param {string} orderType - Order type (BUY or SELL)
|
|
1280
1323
|
* @param {Object} config - Configuration with incrementPercent and weightDistribution
|
|
1281
|
-
* @param {number} [minSize=0] - Minimum size for each allocation
|
|
1282
1324
|
* @param {number} [precision=null] - Asset precision for quantization
|
|
1283
1325
|
* @returns {Array<number>} Array of order sizes
|
|
1284
1326
|
*/
|
|
1285
|
-
function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config,
|
|
1327
|
+
function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config, precision = null) {
|
|
1286
1328
|
if (orderCount <= 0)
|
|
1287
1329
|
return [];
|
|
1288
1330
|
const totalFunds = availableFunds + totalGridAllocation;
|
|
@@ -1293,7 +1335,7 @@ function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderC
|
|
|
1293
1335
|
const incrementFactor = incrementPercent / 100;
|
|
1294
1336
|
const weight = (orderType === ORDER_TYPES.SELL) ? (weightDistribution.sell ?? 0) : (weightDistribution.buy ?? 0);
|
|
1295
1337
|
const reverse = (orderType === ORDER_TYPES.BUY);
|
|
1296
|
-
return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse,
|
|
1338
|
+
return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse, precision);
|
|
1297
1339
|
}
|
|
1298
1340
|
/**
|
|
1299
1341
|
* Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
|
|
@@ -1358,7 +1400,7 @@ function calculateGridSideDivergenceMetric(calculatedOrders, persistedOrders, _s
|
|
|
1358
1400
|
* Works for all pairs — returns the BTS fee budget needed for order operations.
|
|
1359
1401
|
*
|
|
1360
1402
|
* @param {string} assetA - First asset symbol
|
|
1361
|
-
* @param {string} assetB - Second asset symbol (
|
|
1403
|
+
* @param {string} assetB - Second asset symbol (used only to label the fee-cache warning)
|
|
1362
1404
|
* @param {number} totalOrders - Number of orders to create
|
|
1363
1405
|
* @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
|
|
1364
1406
|
* @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
|
|
@@ -1600,6 +1642,15 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
|
|
|
1600
1642
|
let inBandCount = 0;
|
|
1601
1643
|
let firstInBandIdx = null;
|
|
1602
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;
|
|
1603
1654
|
for (let idx = 0; idx < sorted.length; idx++) {
|
|
1604
1655
|
const o = sorted[idx];
|
|
1605
1656
|
if (!o.orderId)
|
|
@@ -1614,6 +1665,9 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
|
|
|
1614
1665
|
minSellPrice = price;
|
|
1615
1666
|
}
|
|
1616
1667
|
else if (options.rejectInBandPlacements) {
|
|
1668
|
+
const slotId = o.id;
|
|
1669
|
+
if (allowedInBand && typeof slotId === 'string' && allowedInBand.has(slotId))
|
|
1670
|
+
continue;
|
|
1617
1671
|
inBandCount++;
|
|
1618
1672
|
if (firstInBandIdx === null) {
|
|
1619
1673
|
firstInBandIdx = idx;
|
|
@@ -1666,8 +1720,11 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
|
|
|
1666
1720
|
* in-progress evacuation; true poison still refuses and structural resync
|
|
1667
1721
|
* falls through to the clean full-grid reset instead of re-ingesting damage.
|
|
1668
1722
|
*/
|
|
1669
|
-
function validatePersistedBoundary(proposedBoundary, orders, gapSlots) {
|
|
1670
|
-
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
|
+
});
|
|
1671
1728
|
}
|
|
1672
1729
|
/**
|
|
1673
1730
|
* Whether a persisted-boundary rejection is the TRANSIENT kind that must not
|
|
@@ -2102,7 +2159,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
|
|
|
2102
2159
|
createdAt: Date.now()
|
|
2103
2160
|
};
|
|
2104
2161
|
}
|
|
2105
|
-
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, 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 };
|
|
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 };
|
|
2106
2163
|
/**
|
|
2107
2164
|
* Round a value to a given factor.
|
|
2108
2165
|
* @param {number} value - Value to round
|