dexbot 1.6.13 → 1.6.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -4
- package/README.md +2 -2
- package/analysis/README.md +6 -6
- package/analysis/tradingview/README.md +2 -1
- package/claw/README.md +7 -7
- package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
- package/claw/modules/claw_catalog.ts +8 -4
- package/claw/modules/dexbot_profiles.ts +59 -15
- package/claw/modules/types.ts +2 -1
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/claw/skills/margin-trading/SKILL.md +1 -1
- package/claw/skills/margin-trading/references/position-management.md +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
- package/dist/dexbot.js +23 -3
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
- package/dist/modules/account_bots.d.ts +10 -6
- package/dist/modules/account_bots.js +13 -10
- package/dist/modules/account_orders.d.ts +36 -4
- package/dist/modules/account_orders.js +76 -5
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
- package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
- package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
- package/dist/modules/bitshares-native/subscriptions.js +1 -1
- package/dist/modules/bot_defaults.d.ts +29 -4
- package/dist/modules/bot_defaults.js +65 -10
- package/dist/modules/bot_settings.d.ts +4 -0
- package/dist/modules/bot_settings.js +58 -21
- package/dist/modules/config.js +6 -1
- package/dist/modules/constants.d.ts +13 -5
- package/dist/modules/constants.js +36 -5
- package/dist/modules/credit_runtime.d.ts +35 -5
- package/dist/modules/credit_runtime.js +219 -38
- package/dist/modules/dexbot_class.d.ts +23 -0
- package/dist/modules/dexbot_class.js +60 -17
- package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
- package/dist/modules/dexbot_cow_runtime.js +350 -64
- package/dist/modules/dexbot_credential_client.d.ts +1 -16
- package/dist/modules/dexbot_credential_client.js +1 -1
- package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
- package/dist/modules/dexbot_fill_runtime.js +16 -8
- package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
- package/dist/modules/dexbot_maintenance_runtime.js +104 -70
- package/dist/modules/dexbot_startup_runtime.js +15 -2
- package/dist/modules/dexbot_state_recovery.js +17 -1
- package/dist/modules/key_store.d.ts +0 -5
- package/dist/modules/key_store.js +1 -1
- package/dist/modules/order/accounting.js +11 -11
- package/dist/modules/order/export.js +4 -4
- package/dist/modules/order/format.d.ts +15 -1
- package/dist/modules/order/format.js +19 -1
- package/dist/modules/order/genesis_policy.d.ts +1 -1
- package/dist/modules/order/genesis_policy.js +1 -1
- package/dist/modules/order/grid.d.ts +141 -12
- package/dist/modules/order/grid.js +666 -92
- package/dist/modules/order/grid_reconcile.d.ts +1 -1
- package/dist/modules/order/grid_reconcile.js +9 -8
- package/dist/modules/order/grid_reconcile_internal.js +61 -58
- package/dist/modules/order/index.d.ts +37 -9
- package/dist/modules/order/logger.js +2 -2
- package/dist/modules/order/manager.d.ts +10 -2
- package/dist/modules/order/manager.js +56 -31
- package/dist/modules/order/strategy.d.ts +2 -2
- package/dist/modules/order/strategy.js +51 -21
- package/dist/modules/order/sync_engine.js +22 -9
- package/dist/modules/order/utils/math.d.ts +101 -29
- package/dist/modules/order/utils/math.js +215 -84
- package/dist/modules/order/utils/order.d.ts +58 -58
- package/dist/modules/order/utils/order.js +135 -106
- package/dist/modules/order/utils/system.d.ts +193 -6
- package/dist/modules/order/utils/system.js +394 -31
- package/dist/modules/order/utils/validate.d.ts +1 -1
- package/dist/modules/order/utils/validate.js +71 -59
- package/dist/modules/runtime_settings.d.ts +1 -1
- package/dist/modules/runtime_settings.js +3 -3
- package/dist/modules/types.d.ts +55 -4
- package/dist/scripts/analyze-credit.js +44 -27
- package/dist/scripts/analyze-orders.d.ts +1 -1
- package/dist/scripts/analyze-orders.js +4 -4
- package/dist/scripts/diagnose-pool-history.js +35 -30
- package/dist/scripts/divergence-calc.js +6 -6
- package/dist/scripts/pnl.js +1 -1
- package/dist/scripts/rich_list.d.ts +18 -0
- package/dist/scripts/rich_list.js +461 -0
- package/dist/scripts/run-tests.js +80 -4
- package/dist/scripts/validate_bots.d.ts +1 -1
- package/dist/scripts/validate_bots.js +3 -3
- package/dist/unlock.d.ts +2 -1
- package/dist/unlock.js +11 -5
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
- package/docs/COW_INVARIANTS.md +12 -6
- package/docs/DEXBOT_COMPARISON.md +7 -7
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
- package/docs/GRID_PRICE_INVARIANT.md +3 -3
- package/docs/GRID_RECALCULATION.md +4 -1
- package/docs/GRID_RECONCILE.md +4 -4
- package/docs/LIFECYCLE.md +11 -11
- package/docs/LOGGING.md +30 -1
- package/docs/MPA_CREDIT_USAGE.md +11 -6
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
- package/docs/README.md +3 -3
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +62 -8
- package/docs/developer_guide.md +12 -3
- package/market_adapter/README.md +4 -4
- package/modules/README.md +1 -1
- package/package.json +2 -1
- package/scripts/README.md +59 -32
- package/tests/README.md +12 -3
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
*
|
|
72
72
|
* ===============================================================================
|
|
73
73
|
*/
|
|
74
|
-
import type { OrderManagerLike, AccountTotals, ManagerFunds,
|
|
74
|
+
import type { OrderManagerLike, AccountTotals, ManagerFunds, CoreOrdersConfig, GridFeeParams, ManagedOrder, AssetPair, GridConfig, GridLimitsLike, WeightDistributionConfig } from '../../types.js';
|
|
75
75
|
interface FeeCacheEntry {
|
|
76
76
|
limitOrderCreate: {
|
|
77
77
|
bts: number;
|
|
@@ -413,10 +413,10 @@ declare function getAssetFeesSafe(assetSymbol: string, assetAmount?: number | nu
|
|
|
413
413
|
* @param {Object} funds - Fund allocation object with virtual, btsFeesOwed properties
|
|
414
414
|
* @param {string} assetA - First asset symbol
|
|
415
415
|
* @param {string} assetB - Second asset symbol
|
|
416
|
-
* @param {Object} [
|
|
416
|
+
* @param {Object} [coreOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
|
|
417
417
|
* @returns {number} Available funds for the side (0 if side invalid or insufficient funds)
|
|
418
418
|
*/
|
|
419
|
-
declare function calculateAvailableFundsValue(side: string, accountTotals: AccountTotals | null | undefined, funds: ManagerFunds, assetA: string | undefined, assetB: string | undefined,
|
|
419
|
+
declare function calculateAvailableFundsValue(side: string, accountTotals: AccountTotals | null | undefined, funds: ManagerFunds, assetA: string | undefined, assetB: string | undefined, coreOrders?: CoreOrdersConfig | null, configMinBtsValue?: number | null, feeParams?: GridFeeParams | null): number;
|
|
420
420
|
/**
|
|
421
421
|
* Adjust an allocated budget for BTS fee reservation.
|
|
422
422
|
* Uses computeBtsFeeImpact for proportional deduction; falls back to 0.5
|
|
@@ -589,19 +589,76 @@ declare function getBtsSide(assetA: string | undefined, assetB: string | undefin
|
|
|
589
589
|
*/
|
|
590
590
|
declare function calculatePriceTolerance(gridPrice: unknown, orderSize: unknown, orderType: string, assets?: AssetPair | null): number | null;
|
|
591
591
|
/**
|
|
592
|
-
*
|
|
593
|
-
*
|
|
594
|
-
*
|
|
595
|
-
*
|
|
596
|
-
*
|
|
597
|
-
*
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
|
|
604
|
-
|
|
592
|
+
* Whether two prices denote the same order-book price LEVEL, using the
|
|
593
|
+
* chain-representable price tolerance derived from both assets' precisions and
|
|
594
|
+
* the order size(s).
|
|
595
|
+
*
|
|
596
|
+
* WHY NOT priceSlotEqual(priceA, priceB, assetPrecision): a price is not an
|
|
597
|
+
* asset AMOUNT. Rounding it through one asset's precision
|
|
598
|
+
* (floatToBlockchainInt) collapses an entire adjacent grid band whenever the
|
|
599
|
+
* OTHER asset has low precision -- e.g. with a precision-4 quote asset both
|
|
600
|
+
* 0.000318 and 0.000319 round to 3, so every BUY after the first looked like a
|
|
601
|
+
* duplicate. The real on-chain price resolution is roughly
|
|
602
|
+
* 10^-precision / orderSize, which is exactly what calculatePriceTolerance
|
|
603
|
+
* derives. Use this for every production "same price level" check.
|
|
604
|
+
*
|
|
605
|
+
* Both types are evaluated and the tighter tolerance is kept (most
|
|
606
|
+
* conservative): a buy-vs-sell comparison where either side uses a
|
|
607
|
+
* precision-0 asset can otherwise produce a tolerance wider than the grid
|
|
608
|
+
* increment and falsely collide adjacent levels.
|
|
609
|
+
*
|
|
610
|
+
* @param {number} priceA - First price
|
|
611
|
+
* @param {number} sizeA - First order size (same side as typeA)
|
|
612
|
+
* @param {string|null|undefined} typeA - First order type (ORDER_TYPES)
|
|
613
|
+
* @param {number} priceB - Second price
|
|
614
|
+
* @param {number} sizeB - Second order size (same side as typeB)
|
|
615
|
+
* @param {string|null|undefined} typeB - Second order type (ORDER_TYPES)
|
|
616
|
+
* @param {object|null} assets - Manager assets (assetA/assetB with precision)
|
|
617
|
+
* @param {number|null} [incrementPercent] - Grid increment; when supplied the
|
|
618
|
+
* tolerance is clamped to half a grid step so a dust-inflated
|
|
619
|
+
* (MIN_ORDER_SIZE_FACTOR floor) tolerance cannot merge adjacent levels.
|
|
620
|
+
* @returns {boolean} True when the two prices sit on the same level
|
|
621
|
+
*/
|
|
622
|
+
declare function pricesOnSameLevel(priceA: number, sizeA: number, typeA: string | null | undefined, priceB: number, sizeB: number, typeB: string | null | undefined, assets?: AssetPair | null, incrementPercent?: number | null | undefined): boolean;
|
|
623
|
+
/**
|
|
624
|
+
* Whether two GENESIS-derived grid prices denote the same ladder level by
|
|
625
|
+
* EXACT identity (with float-noise slack).
|
|
626
|
+
*
|
|
627
|
+
* Grid slot prices are frozen ladder values (bit-identical per level), so
|
|
628
|
+
* exact equality is the correct identity for a grid-vs-grid comparison.
|
|
629
|
+
* Deliberately NOT priceSlotEqual at the asset precision (collapses an
|
|
630
|
+
* adjacent band for a low-precision asset) and NOT the chain tolerance (which
|
|
631
|
+
* can exceed the grid increment and merge two legitimately adjacent levels).
|
|
632
|
+
* Prefer sameGridLevel(genesis) where a ladder is available: it maps a drifted
|
|
633
|
+
* price back to its nearest ladder level. Use pricesOnSameLevel instead when
|
|
634
|
+
* one side is a chain-derived price that may sit a few chain quanta off its
|
|
635
|
+
* level.
|
|
636
|
+
*
|
|
637
|
+
* @param {number} priceA - First grid price
|
|
638
|
+
* @param {number} priceB - Second grid price
|
|
639
|
+
* @returns {boolean} True when both are the same ladder level
|
|
640
|
+
*/
|
|
641
|
+
declare function sameGridPrice(priceA: number, priceB: number): boolean;
|
|
642
|
+
/**
|
|
643
|
+
* Whether two grid prices denote the same ladder level, resolving each price
|
|
644
|
+
* to its nearest level through the frozen genesis ladder when one is supplied.
|
|
645
|
+
* This is robust to a price that was chain-corrected / rounded a quantum off
|
|
646
|
+
* its level: slotIndexForPrice maps it back to the level it came from, while a
|
|
647
|
+
* price that genuinely moved to another level resolves to a different index.
|
|
648
|
+
*
|
|
649
|
+
* PRECONDITION / HARDENING: slotIndexForPrice CLAMPS an out-of-rail price onto
|
|
650
|
+
* the edge levels, so two distinct out-of-rail prices would otherwise resolve
|
|
651
|
+
* "equal". This helper therefore only uses slot identity when BOTH prices sit
|
|
652
|
+
* inside [levels[0], levels[N-1]]; otherwise it falls back to exact-level
|
|
653
|
+
* identity (sameGridPrice, with float-noise slack). Callers pass in-rail grid
|
|
654
|
+
* prices today, but the guard makes out-of-rail misuse safe.
|
|
655
|
+
*
|
|
656
|
+
* @param {number} priceA - First grid price
|
|
657
|
+
* @param {number} priceB - Second grid price
|
|
658
|
+
* @param {unknown} genesis - Frozen genesis ladder (`manager._genesis`)
|
|
659
|
+
* @returns {boolean} True when both prices resolve to the same ladder level
|
|
660
|
+
*/
|
|
661
|
+
declare function sameGridLevel(priceA: number, priceB: number, genesis: unknown): boolean;
|
|
605
662
|
/**
|
|
606
663
|
* Find an opposite-side order that a candidate placement would CROSS.
|
|
607
664
|
*
|
|
@@ -615,10 +672,9 @@ declare function findPriceCollision(items: Iterable<CollisionItem>, excludeId: s
|
|
|
615
672
|
* sell ladder was re-priced into marketable buys, triggering a fatal
|
|
616
673
|
* fund assertion).
|
|
617
674
|
*
|
|
618
|
-
* Unlike
|
|
619
|
-
*
|
|
620
|
-
*
|
|
621
|
-
* cancelled earlier in the same plan).
|
|
675
|
+
* Unlike a same-price check, this catches crossings at ANY price overlap and
|
|
676
|
+
* is intended for the re-pricing UPDATE / CREATE paths. The caller decides the
|
|
677
|
+
* exemption policy (e.g. crossed orders cancelled earlier in the same plan).
|
|
622
678
|
*
|
|
623
679
|
* @param {Iterable<any>} items - Candidate orders (e.g. manager.orders.values())
|
|
624
680
|
* @param {number} price - Candidate placement price
|
|
@@ -796,8 +852,17 @@ declare function calculateGapSlots(incrementPercent: number | undefined, targetS
|
|
|
796
852
|
/**
|
|
797
853
|
* Calculate sell start index from boundary index and gap slots.
|
|
798
854
|
* sellStartIdx = boundaryIdx + gapSlots + 1
|
|
855
|
+
*
|
|
856
|
+
* Absent-aware: Number(null) === 0 and Number('') === 0 would read "no
|
|
857
|
+
* boundary" as boundary 0 and manufacture a SELL-rail start at gapSlots+1.
|
|
858
|
+
* Unknown geometry (null/undefined/'') returns NaN so any unguarded caller
|
|
859
|
+
* fails closed via Number.isFinite instead of silently rail-biasing slot 0.
|
|
860
|
+
* Every current caller guards first (resolveGapBand, isSlotInRail,
|
|
861
|
+
* isSlotIndexInGapBand, geometryTypeForSlotIndex, the COW stamp paths);
|
|
862
|
+
* this carries the same contract in the helper itself so a future caller
|
|
863
|
+
* cannot bypass it. A genuine 0 boundary still yields gapSlots + 1.
|
|
799
864
|
*/
|
|
800
|
-
declare function getSellStartIdx(boundaryIdx: number | null, gapSlots: number | null): number;
|
|
865
|
+
declare function getSellStartIdx(boundaryIdx: number | string | null | undefined, gapSlots: number | string | null | undefined): number;
|
|
801
866
|
/**
|
|
802
867
|
* Resolve the configured gap-slot count for a manager-like object.
|
|
803
868
|
* Single source of truth for the `_gapSlots ?? calculateGapSlots(config)`
|
|
@@ -930,7 +995,7 @@ declare function validatePersistedBoundary(proposedBoundary: number | null | und
|
|
|
930
995
|
* over 2-3 cycles, so a snapshot taken mid-evacuation (or stale by one
|
|
931
996
|
* crawl, as in recovery-before-CREATE) legitimately reports this. Nuking
|
|
932
997
|
* the snapshot for it discards the boundary progression, pending crawls,
|
|
933
|
-
* streaks and the queued evacuation — the exact sabotage loop seen in
|
|
998
|
+
* streaks and the queued evacuation — the exact sabotage loop seen in <bot>
|
|
934
999
|
* 2026-09-13 (GAP-EVAC flags slot-96, COW plans 96→116, stale snapshot with
|
|
935
1000
|
* slot-94 still stranded fails validation, structural resync wipes the
|
|
936
1001
|
* plan). All other reasons (ceiling/range/crossed-book/...) are structural
|
|
@@ -974,7 +1039,7 @@ declare function countGapBandSpread(manager: OrderManagerLike, orders: Iterable<
|
|
|
974
1039
|
* (grid_reconcile_internal.ts), and the COW divergence correction (system.ts).
|
|
975
1040
|
* Drift between those copies is what let a fund-driven boundary shift leave a
|
|
976
1041
|
* SPREAD GUARD-typed stray inside the gap as "closest to market" — collapsing
|
|
977
|
-
* the spread (
|
|
1042
|
+
* the spread (<bot>: boundary 107→110 left the sell rail parked at 111-130
|
|
978
1043
|
* with the bottom three, 111-113, inside the new spread gap; real spread 0.5%
|
|
979
1044
|
* vs the 2.0% target).
|
|
980
1045
|
*
|
|
@@ -1076,11 +1141,18 @@ declare function slotIdForPrice(price: number, genesis: GridGenesis): string;
|
|
|
1076
1141
|
* slotIndexForPrice clamps out-of-range prices onto the edge slots (0/N-1),
|
|
1077
1142
|
* so callers MUST check this before adopting or duplicate-matching: a
|
|
1078
1143
|
* below-grid buy is not slot-0 and an above-grid sell is not slot-(N-1).
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1082
|
-
|
|
1083
|
-
|
|
1144
|
+
* Only genuine float dust at the edge is excused; anything further out is
|
|
1145
|
+
* out-of-grid -> hold/defer, never adopt or cancel as a duplicate.
|
|
1146
|
+
*
|
|
1147
|
+
* The edge excuse is the chain-representable tolerance (pricesOnSameLevel),
|
|
1148
|
+
* clamped to half a ladder step. Deliberately NOT priceSlotEqual at the asset
|
|
1149
|
+
* precision: a price is not an amount, so a precision-4 asset rounds a whole
|
|
1150
|
+
* adjacent band below the rail onto the edge and wrongly classifies a
|
|
1151
|
+
* dip-protection level as in-grid (fail-open). When assets/type are missing,
|
|
1152
|
+
* only float noise at the edge is excused (exact-level identity), so an
|
|
1153
|
+
* unjudgeable outside price stays out-of-grid (fail-closed).
|
|
1154
|
+
*/
|
|
1155
|
+
declare function isChainPriceOutOfGrid(price: number, genesis: GridGenesis, size?: number, type?: string | null, assets?: AssetPair | null): boolean;
|
|
1084
1156
|
declare function assertSlotPriceInvariant(slot: unknown, genesis: GridGenesis): void;
|
|
1085
1157
|
declare function priceSlotEqual(a: number, b: number, precision: number): boolean;
|
|
1086
1158
|
/**
|
|
@@ -1106,7 +1178,7 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
|
|
|
1106
1178
|
declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
|
|
1107
1179
|
declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
|
|
1108
1180
|
export type { FeeCacheEntry };
|
|
1109
|
-
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,
|
|
1181
|
+
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 };
|
|
1110
1182
|
/**
|
|
1111
1183
|
* Round a value to a given factor.
|
|
1112
1184
|
* @param {number} value - Value to round
|
|
@@ -429,10 +429,10 @@ function getAssetFeesSafe(assetSymbol, assetAmount = null, isMaker = true) {
|
|
|
429
429
|
* @param {Object} funds - Fund allocation object with virtual, btsFeesOwed properties
|
|
430
430
|
* @param {string} assetA - First asset symbol
|
|
431
431
|
* @param {string} assetB - Second asset symbol
|
|
432
|
-
* @param {Object} [
|
|
432
|
+
* @param {Object} [coreOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
|
|
433
433
|
* @returns {number} Available funds for the side (0 if side invalid or insufficient funds)
|
|
434
434
|
*/
|
|
435
|
-
function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB,
|
|
435
|
+
function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB, coreOrders = null, configMinBtsValue = null, feeParams = null) {
|
|
436
436
|
if (side !== 'buy' && side !== 'sell')
|
|
437
437
|
return 0;
|
|
438
438
|
const chainFree = toFiniteNumber(side === 'buy' ? accountTotals?.buyFree : accountTotals?.sellFree);
|
|
@@ -441,17 +441,17 @@ function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB
|
|
|
441
441
|
const btsSide = getBtsSide(assetA, assetB);
|
|
442
442
|
const btsReservationMultiplier = feeParams?.BTS_RESERVATION_MULTIPLIER ?? FEE_PARAMETERS.BTS_RESERVATION_MULTIPLIER;
|
|
443
443
|
let btsFeesReservation = 0;
|
|
444
|
-
if (btsSide === side &&
|
|
445
|
-
const targetBuy = Math.max(0, toFiniteNumber(
|
|
446
|
-
const targetSell = Math.max(0, toFiniteNumber(
|
|
444
|
+
if (btsSide === side && coreOrders) {
|
|
445
|
+
const targetBuy = Math.max(0, toFiniteNumber(coreOrders?.buy, 1));
|
|
446
|
+
const targetSell = Math.max(0, toFiniteNumber(coreOrders?.sell, 1));
|
|
447
447
|
const totalTargetOrders = targetBuy + targetSell;
|
|
448
448
|
btsFeesReservation = calculateOrderCreationFees(assetA, assetB, totalTargetOrders, btsReservationMultiplier);
|
|
449
449
|
}
|
|
450
450
|
const currentFeesOwed = (btsSide === side) ? btsFeesOwed : 0;
|
|
451
451
|
// Non-BTS pair: reserve proportional share for BTS fee budget
|
|
452
|
-
if (!btsSide &&
|
|
453
|
-
const targetBuy = Math.max(0, toFiniteNumber(
|
|
454
|
-
const targetSell = Math.max(0, toFiniteNumber(
|
|
452
|
+
if (!btsSide && coreOrders && funds?.btsBalance != null) {
|
|
453
|
+
const targetBuy = Math.max(0, toFiniteNumber(coreOrders?.buy, 1));
|
|
454
|
+
const targetSell = Math.max(0, toFiniteNumber(coreOrders?.sell, 1));
|
|
455
455
|
const totalTargetOrders = targetBuy + targetSell;
|
|
456
456
|
const formulaBudget = calculateOrderCreationFees(assetA, assetB, totalTargetOrders, btsReservationMultiplier);
|
|
457
457
|
const btsFree = toFiniteNumber(funds?.btsBalance?.free, 0);
|
|
@@ -804,49 +804,140 @@ function calculatePriceTolerance(gridPrice, orderSize, orderType, assets = null)
|
|
|
804
804
|
return Math.min(tolerance, maxTolerance);
|
|
805
805
|
}
|
|
806
806
|
/**
|
|
807
|
-
*
|
|
808
|
-
*
|
|
809
|
-
*
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
*
|
|
814
|
-
*
|
|
815
|
-
*
|
|
816
|
-
*
|
|
817
|
-
*
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
807
|
+
* Whether two prices denote the same order-book price LEVEL, using the
|
|
808
|
+
* chain-representable price tolerance derived from both assets' precisions and
|
|
809
|
+
* the order size(s).
|
|
810
|
+
*
|
|
811
|
+
* WHY NOT priceSlotEqual(priceA, priceB, assetPrecision): a price is not an
|
|
812
|
+
* asset AMOUNT. Rounding it through one asset's precision
|
|
813
|
+
* (floatToBlockchainInt) collapses an entire adjacent grid band whenever the
|
|
814
|
+
* OTHER asset has low precision -- e.g. with a precision-4 quote asset both
|
|
815
|
+
* 0.000318 and 0.000319 round to 3, so every BUY after the first looked like a
|
|
816
|
+
* duplicate. The real on-chain price resolution is roughly
|
|
817
|
+
* 10^-precision / orderSize, which is exactly what calculatePriceTolerance
|
|
818
|
+
* derives. Use this for every production "same price level" check.
|
|
819
|
+
*
|
|
820
|
+
* Both types are evaluated and the tighter tolerance is kept (most
|
|
821
|
+
* conservative): a buy-vs-sell comparison where either side uses a
|
|
822
|
+
* precision-0 asset can otherwise produce a tolerance wider than the grid
|
|
823
|
+
* increment and falsely collide adjacent levels.
|
|
824
|
+
*
|
|
825
|
+
* @param {number} priceA - First price
|
|
826
|
+
* @param {number} sizeA - First order size (same side as typeA)
|
|
827
|
+
* @param {string|null|undefined} typeA - First order type (ORDER_TYPES)
|
|
828
|
+
* @param {number} priceB - Second price
|
|
829
|
+
* @param {number} sizeB - Second order size (same side as typeB)
|
|
830
|
+
* @param {string|null|undefined} typeB - Second order type (ORDER_TYPES)
|
|
831
|
+
* @param {object|null} assets - Manager assets (assetA/assetB with precision)
|
|
832
|
+
* @param {number|null} [incrementPercent] - Grid increment; when supplied the
|
|
833
|
+
* tolerance is clamped to half a grid step so a dust-inflated
|
|
834
|
+
* (MIN_ORDER_SIZE_FACTOR floor) tolerance cannot merge adjacent levels.
|
|
835
|
+
* @returns {boolean} True when the two prices sit on the same level
|
|
836
|
+
*/
|
|
837
|
+
function pricesOnSameLevel(priceA, sizeA, typeA, priceB, sizeB, typeB, assets = null, incrementPercent = null) {
|
|
838
|
+
const pa = Number(priceA);
|
|
839
|
+
const pb = Number(priceB);
|
|
840
|
+
if (!Number.isFinite(pa) || !Number.isFinite(pb))
|
|
841
|
+
return pa === pb;
|
|
842
|
+
const size = Math.max(Number(sizeA) || 0, Number(sizeB) || 0);
|
|
843
|
+
const gridPrice = Math.min(pa, pb);
|
|
844
|
+
let tolerance = null;
|
|
845
|
+
for (const type of [typeA, typeB]) {
|
|
846
|
+
if (type == null)
|
|
824
847
|
continue;
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
continue;
|
|
829
|
-
// Compute tolerance for both the target order's type and the
|
|
830
|
-
// candidate item's type, then take the minimum (most conservative).
|
|
831
|
-
// Without this, a buy-vs-sell comparison where one side uses a
|
|
832
|
-
// precision-0 asset can produce tolerance > grid increment from
|
|
833
|
-
// the MIN_ORDER_SIZE_FACTOR=50 floor alone, causing adjacent grid
|
|
834
|
-
// levels to falsely collide (see validateCreateTargetSlots layer 2
|
|
835
|
-
// comment for the full analysis).
|
|
836
|
-
const toleranceTarget = calculatePriceTolerance(Math.min(price, targetPrice), Math.max(size, targetSize), targetType, assets);
|
|
837
|
-
let tolerance = toleranceTarget;
|
|
838
|
-
const itemType = item.type ?? item.order?.type;
|
|
839
|
-
if (toleranceTarget != null && itemType != null) {
|
|
840
|
-
const toleranceItem = calculatePriceTolerance(Math.min(price, targetPrice), Math.max(size, targetSize), itemType, assets);
|
|
841
|
-
if (toleranceItem != null) {
|
|
842
|
-
tolerance = Math.min(toleranceTarget, toleranceItem);
|
|
843
|
-
}
|
|
848
|
+
let t = null;
|
|
849
|
+
try {
|
|
850
|
+
t = calculatePriceTolerance(gridPrice, size, type, assets);
|
|
844
851
|
}
|
|
845
|
-
|
|
846
|
-
|
|
852
|
+
catch {
|
|
853
|
+
t = null;
|
|
854
|
+
}
|
|
855
|
+
if (t != null && Number.isFinite(t)) {
|
|
856
|
+
tolerance = tolerance == null ? t : Math.min(tolerance, t);
|
|
847
857
|
}
|
|
848
858
|
}
|
|
849
|
-
|
|
859
|
+
if (tolerance == null)
|
|
860
|
+
return pa === pb;
|
|
861
|
+
// Hard cap: never let the tolerance span more than half a grid step. The
|
|
862
|
+
// precision/floor maths above can otherwise exceed the increment for
|
|
863
|
+
// dust-sized or low-precision orders, merging two legitimately adjacent
|
|
864
|
+
// levels (the caller passes the increment when it has one).
|
|
865
|
+
const inc = Number(incrementPercent);
|
|
866
|
+
if (Number.isFinite(inc) && inc > 0) {
|
|
867
|
+
tolerance = Math.min(tolerance, Math.abs(gridPrice) * (inc / 100) * 0.5);
|
|
868
|
+
}
|
|
869
|
+
return Math.abs(pa - pb) <= tolerance;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Relative slack for grid price identity. Large enough to absorb float noise
|
|
873
|
+
* (re-serialization, a stored value recomputed through a different but
|
|
874
|
+
* algebraically equivalent path) yet far below any real grid increment, so it
|
|
875
|
+
* cannot merge two genuinely distinct ladder levels.
|
|
876
|
+
*/
|
|
877
|
+
const GRID_PRICE_REL_EPSILON = 1e-9;
|
|
878
|
+
/**
|
|
879
|
+
* Whether two GENESIS-derived grid prices denote the same ladder level by
|
|
880
|
+
* EXACT identity (with float-noise slack).
|
|
881
|
+
*
|
|
882
|
+
* Grid slot prices are frozen ladder values (bit-identical per level), so
|
|
883
|
+
* exact equality is the correct identity for a grid-vs-grid comparison.
|
|
884
|
+
* Deliberately NOT priceSlotEqual at the asset precision (collapses an
|
|
885
|
+
* adjacent band for a low-precision asset) and NOT the chain tolerance (which
|
|
886
|
+
* can exceed the grid increment and merge two legitimately adjacent levels).
|
|
887
|
+
* Prefer sameGridLevel(genesis) where a ladder is available: it maps a drifted
|
|
888
|
+
* price back to its nearest ladder level. Use pricesOnSameLevel instead when
|
|
889
|
+
* one side is a chain-derived price that may sit a few chain quanta off its
|
|
890
|
+
* level.
|
|
891
|
+
*
|
|
892
|
+
* @param {number} priceA - First grid price
|
|
893
|
+
* @param {number} priceB - Second grid price
|
|
894
|
+
* @returns {boolean} True when both are the same ladder level
|
|
895
|
+
*/
|
|
896
|
+
function sameGridPrice(priceA, priceB) {
|
|
897
|
+
const a = Number(priceA);
|
|
898
|
+
const b = Number(priceB);
|
|
899
|
+
if (!Number.isFinite(a) || !Number.isFinite(b))
|
|
900
|
+
return a === b;
|
|
901
|
+
if (a === b)
|
|
902
|
+
return true;
|
|
903
|
+
return Math.abs(a - b) <= GRID_PRICE_REL_EPSILON * Math.max(1, Math.abs(a), Math.abs(b));
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Whether two grid prices denote the same ladder level, resolving each price
|
|
907
|
+
* to its nearest level through the frozen genesis ladder when one is supplied.
|
|
908
|
+
* This is robust to a price that was chain-corrected / rounded a quantum off
|
|
909
|
+
* its level: slotIndexForPrice maps it back to the level it came from, while a
|
|
910
|
+
* price that genuinely moved to another level resolves to a different index.
|
|
911
|
+
*
|
|
912
|
+
* PRECONDITION / HARDENING: slotIndexForPrice CLAMPS an out-of-rail price onto
|
|
913
|
+
* the edge levels, so two distinct out-of-rail prices would otherwise resolve
|
|
914
|
+
* "equal". This helper therefore only uses slot identity when BOTH prices sit
|
|
915
|
+
* inside [levels[0], levels[N-1]]; otherwise it falls back to exact-level
|
|
916
|
+
* identity (sameGridPrice, with float-noise slack). Callers pass in-rail grid
|
|
917
|
+
* prices today, but the guard makes out-of-rail misuse safe.
|
|
918
|
+
*
|
|
919
|
+
* @param {number} priceA - First grid price
|
|
920
|
+
* @param {number} priceB - Second grid price
|
|
921
|
+
* @param {unknown} genesis - Frozen genesis ladder (`manager._genesis`)
|
|
922
|
+
* @returns {boolean} True when both prices resolve to the same ladder level
|
|
923
|
+
*/
|
|
924
|
+
function sameGridLevel(priceA, priceB, genesis) {
|
|
925
|
+
const a = Number(priceA);
|
|
926
|
+
const b = Number(priceB);
|
|
927
|
+
const levels = genesis?.priceLevels;
|
|
928
|
+
if (Array.isArray(levels) && levels.length > 0) {
|
|
929
|
+
const lo = Number(levels[0]);
|
|
930
|
+
const hi = Number(levels[levels.length - 1]);
|
|
931
|
+
const inRail = (p) => Number.isFinite(p) && p >= lo && p <= hi;
|
|
932
|
+
if (!inRail(a) || !inRail(b))
|
|
933
|
+
return sameGridPrice(a, b);
|
|
934
|
+
try {
|
|
935
|
+
const g = genesis;
|
|
936
|
+
return slotIndexForPrice(a, g) === slotIndexForPrice(b, g);
|
|
937
|
+
}
|
|
938
|
+
catch { /* unjudgeable ladder — fall through to exact-level identity */ }
|
|
939
|
+
}
|
|
940
|
+
return sameGridPrice(a, b);
|
|
850
941
|
}
|
|
851
942
|
/**
|
|
852
943
|
* Find an opposite-side order that a candidate placement would CROSS.
|
|
@@ -861,10 +952,9 @@ function findPriceCollision(items, excludeId, targetPrice, targetSize, targetTyp
|
|
|
861
952
|
* sell ladder was re-priced into marketable buys, triggering a fatal
|
|
862
953
|
* fund assertion).
|
|
863
954
|
*
|
|
864
|
-
* Unlike
|
|
865
|
-
*
|
|
866
|
-
*
|
|
867
|
-
* cancelled earlier in the same plan).
|
|
955
|
+
* Unlike a same-price check, this catches crossings at ANY price overlap and
|
|
956
|
+
* is intended for the re-pricing UPDATE / CREATE paths. The caller decides the
|
|
957
|
+
* exemption policy (e.g. crossed orders cancelled earlier in the same plan).
|
|
868
958
|
*
|
|
869
959
|
* @param {Iterable<any>} items - Candidate orders (e.g. manager.orders.values())
|
|
870
960
|
* @param {number} price - Candidate placement price
|
|
@@ -1305,9 +1395,22 @@ function calculateGapSlots(incrementPercent, targetSpreadPercent, gridLimits = {
|
|
|
1305
1395
|
/**
|
|
1306
1396
|
* Calculate sell start index from boundary index and gap slots.
|
|
1307
1397
|
* sellStartIdx = boundaryIdx + gapSlots + 1
|
|
1398
|
+
*
|
|
1399
|
+
* Absent-aware: Number(null) === 0 and Number('') === 0 would read "no
|
|
1400
|
+
* boundary" as boundary 0 and manufacture a SELL-rail start at gapSlots+1.
|
|
1401
|
+
* Unknown geometry (null/undefined/'') returns NaN so any unguarded caller
|
|
1402
|
+
* fails closed via Number.isFinite instead of silently rail-biasing slot 0.
|
|
1403
|
+
* Every current caller guards first (resolveGapBand, isSlotInRail,
|
|
1404
|
+
* isSlotIndexInGapBand, geometryTypeForSlotIndex, the COW stamp paths);
|
|
1405
|
+
* this carries the same contract in the helper itself so a future caller
|
|
1406
|
+
* cannot bypass it. A genuine 0 boundary still yields gapSlots + 1.
|
|
1308
1407
|
*/
|
|
1309
1408
|
function getSellStartIdx(boundaryIdx, gapSlots) {
|
|
1310
|
-
|
|
1409
|
+
const b = Format.toKnownNumber(boundaryIdx);
|
|
1410
|
+
const g = Format.toKnownNumber(gapSlots);
|
|
1411
|
+
if (!Number.isFinite(b) || !Number.isFinite(g))
|
|
1412
|
+
return NaN;
|
|
1413
|
+
return b + g + 1;
|
|
1311
1414
|
}
|
|
1312
1415
|
/**
|
|
1313
1416
|
* Resolve the configured gap-slot count for a manager-like object.
|
|
@@ -1316,9 +1419,13 @@ function getSellStartIdx(boundaryIdx, gapSlots) {
|
|
|
1316
1419
|
* two can never disagree on band width.
|
|
1317
1420
|
*/
|
|
1318
1421
|
function resolveGapSlots(manager) {
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1422
|
+
// Absent-aware: Number('') === 0 is finite, so a '' _gapSlots would pass
|
|
1423
|
+
// the finite test as a valid 0 and collapse the band. '' is unknown →
|
|
1424
|
+
// fall back to the config-derived gap (same contract as
|
|
1425
|
+
// consumePendingFillCrawls' dc87ce01 fallback).
|
|
1426
|
+
const raw = Format.toKnownNumber(manager._gapSlots);
|
|
1427
|
+
if (Number.isFinite(raw)) {
|
|
1428
|
+
return Math.max(0, Math.floor(raw));
|
|
1322
1429
|
}
|
|
1323
1430
|
return calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
|
|
1324
1431
|
}
|
|
@@ -1336,13 +1443,11 @@ function resolveGapSlots(manager) {
|
|
|
1336
1443
|
*/
|
|
1337
1444
|
function resolveGapBand(manager) {
|
|
1338
1445
|
const gapSlots = resolveGapSlots(manager);
|
|
1339
|
-
//
|
|
1340
|
-
//
|
|
1341
|
-
//
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
}
|
|
1345
|
-
const raw = Number(manager.boundaryIdx);
|
|
1446
|
+
// Absent-aware coercion: Number(null)/Number('') === 0 would silently treat
|
|
1447
|
+
// "no boundary" as boundary 0 — a valid index that biases all slots to the
|
|
1448
|
+
// SELL rail. toKnownNumber keeps null/undefined/'' as NaN so the unknown
|
|
1449
|
+
// state is detectable, while a genuine boundary 0 still returns 0.
|
|
1450
|
+
const raw = Format.toKnownNumber(manager.boundaryIdx);
|
|
1346
1451
|
if (!Number.isFinite(raw)) {
|
|
1347
1452
|
return { gapSlots, boundaryIdx: null, sellStartIdx: null };
|
|
1348
1453
|
}
|
|
@@ -1401,7 +1506,15 @@ const BOUNDARY_REJECT_PLACED_IN_BAND = 'placed_order_in_band';
|
|
|
1401
1506
|
* is a stable short code and `detail` carries indices/prices for logs.
|
|
1402
1507
|
*/
|
|
1403
1508
|
function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}) {
|
|
1404
|
-
|
|
1509
|
+
// Absent-aware: null/undefined/'' means "no proposal" (ok), NOT boundary 0,
|
|
1510
|
+
// otherwise Number('') === 0 would self-legalize a fake boundary 0 commit.
|
|
1511
|
+
// Everything else non-numeric stays FAIL-CLOSED (corrupt/garbage, never
|
|
1512
|
+
// ok): this gate also backs validatePersistedBoundary — the disk-trust
|
|
1513
|
+
// boundary where a poison value must surface as a rejection (rebuild),
|
|
1514
|
+
// not silently pass as "no proposal". Callers pass number | null; the
|
|
1515
|
+
// '' branch only exists because '' would otherwise coerce to 0 via
|
|
1516
|
+
// Number() and read as a valid boundary index.
|
|
1517
|
+
if (proposedBoundary === '' || proposedBoundary == null)
|
|
1405
1518
|
return { ok: true };
|
|
1406
1519
|
const raw = Number(proposedBoundary);
|
|
1407
1520
|
if (!Number.isFinite(raw) || !Number.isInteger(raw)) {
|
|
@@ -1528,7 +1641,7 @@ function validatePersistedBoundary(proposedBoundary, orders, gapSlots) {
|
|
|
1528
1641
|
* over 2-3 cycles, so a snapshot taken mid-evacuation (or stale by one
|
|
1529
1642
|
* crawl, as in recovery-before-CREATE) legitimately reports this. Nuking
|
|
1530
1643
|
* the snapshot for it discards the boundary progression, pending crawls,
|
|
1531
|
-
* streaks and the queued evacuation — the exact sabotage loop seen in
|
|
1644
|
+
* streaks and the queued evacuation — the exact sabotage loop seen in <bot>
|
|
1532
1645
|
* 2026-09-13 (GAP-EVAC flags slot-96, COW plans 96→116, stale snapshot with
|
|
1533
1646
|
* slot-94 still stranded fails validation, structural resync wipes the
|
|
1534
1647
|
* plan). All other reasons (ceiling/range/crossed-book/...) are structural
|
|
@@ -1585,7 +1698,7 @@ function countGapBandSpread(manager, orders, resolveIndex) {
|
|
|
1585
1698
|
* (grid_reconcile_internal.ts), and the COW divergence correction (system.ts).
|
|
1586
1699
|
* Drift between those copies is what let a fund-driven boundary shift leave a
|
|
1587
1700
|
* SPREAD GUARD-typed stray inside the gap as "closest to market" — collapsing
|
|
1588
|
-
* the spread (
|
|
1701
|
+
* the spread (<bot>: boundary 107→110 left the sell rail parked at 111-130
|
|
1589
1702
|
* with the bottom three, 111-113, inside the new spread gap; real spread 0.5%
|
|
1590
1703
|
* vs the 2.0% target).
|
|
1591
1704
|
*
|
|
@@ -1605,17 +1718,25 @@ function countGapBandSpread(manager, orders, resolveIndex) {
|
|
|
1605
1718
|
* sits provably outside the rail.
|
|
1606
1719
|
*/
|
|
1607
1720
|
function isSlotInRail(boundaryIdx, gapSlots, orderType, slot) {
|
|
1608
|
-
|
|
1721
|
+
// Absent-aware: ''/null/undefined is unknown geometry → fail open, never a
|
|
1722
|
+
// boundary of 0 (Number('') === 0 would otherwise exclude valid slots).
|
|
1723
|
+
const boundary = Format.toKnownNumber(boundaryIdx);
|
|
1724
|
+
if (!Number.isFinite(boundary))
|
|
1609
1725
|
return true;
|
|
1610
1726
|
const parsed = parseSlotIndex(slot?.id);
|
|
1611
1727
|
if (parsed === null)
|
|
1612
1728
|
return true;
|
|
1613
1729
|
const idx = parsed;
|
|
1614
1730
|
if (orderType === ORDER_TYPES.BUY)
|
|
1615
|
-
return idx <=
|
|
1731
|
+
return idx <= boundary;
|
|
1616
1732
|
if (orderType !== ORDER_TYPES.SELL)
|
|
1617
1733
|
return true;
|
|
1618
|
-
|
|
1734
|
+
// The SELL rail needs the gap width; unknown gap → cannot derive sellStart
|
|
1735
|
+
// → fail open (same contract as the unknown-boundary branch above).
|
|
1736
|
+
const gap = Format.toKnownNumber(gapSlots);
|
|
1737
|
+
if (!Number.isFinite(gap))
|
|
1738
|
+
return true;
|
|
1739
|
+
const sellStartIdx = getSellStartIdx(boundary, gap);
|
|
1619
1740
|
if (!Number.isFinite(sellStartIdx))
|
|
1620
1741
|
return true;
|
|
1621
1742
|
return idx >= sellStartIdx;
|
|
@@ -1632,14 +1753,11 @@ function isSlotInRail(boundaryIdx, gapSlots, orderType, slot) {
|
|
|
1632
1753
|
* @returns {boolean} True when the index is inside the gap band
|
|
1633
1754
|
*/
|
|
1634
1755
|
function isSlotIndexInGapBand(idx, boundaryIdx, gapSlots) {
|
|
1635
|
-
//
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
const n = Number(idx);
|
|
1641
|
-
const b = Number(boundaryIdx);
|
|
1642
|
-
const g = Number(gapSlots);
|
|
1756
|
+
// Absent-aware: Number(null)/Number('') === 0 must never read as slot 0,
|
|
1757
|
+
// and an unknown gap width must not collapse the band (null → 0).
|
|
1758
|
+
const n = Format.toKnownNumber(idx);
|
|
1759
|
+
const b = Format.toKnownNumber(boundaryIdx);
|
|
1760
|
+
const g = Format.toKnownNumber(gapSlots);
|
|
1643
1761
|
if (!Number.isFinite(n) || !Number.isFinite(b) || !Number.isFinite(g))
|
|
1644
1762
|
return false;
|
|
1645
1763
|
const sellStartIdx = getSellStartIdx(b, g);
|
|
@@ -1810,11 +1928,18 @@ function slotIdForPrice(price, genesis) {
|
|
|
1810
1928
|
* slotIndexForPrice clamps out-of-range prices onto the edge slots (0/N-1),
|
|
1811
1929
|
* so callers MUST check this before adopting or duplicate-matching: a
|
|
1812
1930
|
* below-grid buy is not slot-0 and an above-grid sell is not slot-(N-1).
|
|
1813
|
-
*
|
|
1814
|
-
*
|
|
1815
|
-
*
|
|
1816
|
-
|
|
1817
|
-
|
|
1931
|
+
* Only genuine float dust at the edge is excused; anything further out is
|
|
1932
|
+
* out-of-grid -> hold/defer, never adopt or cancel as a duplicate.
|
|
1933
|
+
*
|
|
1934
|
+
* The edge excuse is the chain-representable tolerance (pricesOnSameLevel),
|
|
1935
|
+
* clamped to half a ladder step. Deliberately NOT priceSlotEqual at the asset
|
|
1936
|
+
* precision: a price is not an amount, so a precision-4 asset rounds a whole
|
|
1937
|
+
* adjacent band below the rail onto the edge and wrongly classifies a
|
|
1938
|
+
* dip-protection level as in-grid (fail-open). When assets/type are missing,
|
|
1939
|
+
* only float noise at the edge is excused (exact-level identity), so an
|
|
1940
|
+
* unjudgeable outside price stays out-of-grid (fail-closed).
|
|
1941
|
+
*/
|
|
1942
|
+
function isChainPriceOutOfGrid(price, genesis, size = 0, type = null, assets = null) {
|
|
1818
1943
|
const levels = genesis?.priceLevels;
|
|
1819
1944
|
if (!Array.isArray(levels) || levels.length === 0)
|
|
1820
1945
|
return false;
|
|
@@ -1822,9 +1947,15 @@ function isChainPriceOutOfGrid(price, genesis, precision) {
|
|
|
1822
1947
|
return false;
|
|
1823
1948
|
const min = levels[0];
|
|
1824
1949
|
const max = levels[levels.length - 1];
|
|
1825
|
-
|
|
1950
|
+
const incrementPercent = levels.length > 1 && Number(levels[0]) > 0
|
|
1951
|
+
? ((Number(levels[1]) - Number(levels[0])) / Number(levels[0])) * 100
|
|
1952
|
+
: null;
|
|
1953
|
+
const onEdge = (edge) => (assets != null && type != null)
|
|
1954
|
+
? pricesOnSameLevel(price, size, type, edge, size, type, assets, incrementPercent)
|
|
1955
|
+
: sameGridPrice(price, edge);
|
|
1956
|
+
if (price < min && !onEdge(min))
|
|
1826
1957
|
return true;
|
|
1827
|
-
if (price > max && !
|
|
1958
|
+
if (price > max && !onEdge(max))
|
|
1828
1959
|
return true;
|
|
1829
1960
|
return false;
|
|
1830
1961
|
}
|
|
@@ -1933,7 +2064,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
|
|
|
1933
2064
|
createdAt: Date.now()
|
|
1934
2065
|
};
|
|
1935
2066
|
}
|
|
1936
|
-
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,
|
|
2067
|
+
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 };
|
|
1937
2068
|
/**
|
|
1938
2069
|
* Round a value to a given factor.
|
|
1939
2070
|
* @param {number} value - Value to round
|