dexbot 1.6.14 → 1.6.16
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 +60 -4
- package/README.md +4 -4
- package/analysis/README.md +6 -6
- package/analysis/tradingview/README.md +2 -1
- package/claw/README.md +7 -7
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
- package/claw/modules/chain_queries.ts +3 -3
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
- package/dist/analysis/bot_key_utils.js +9 -7
- package/dist/analysis/chart_utils.d.ts +9 -2
- package/dist/analysis/chart_utils.js +51 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
- package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
- package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
- package/dist/dexbot.js +112 -141
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
- package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
- package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
- package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
- package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
- package/dist/market_adapter/inputs/window_cache.js +53 -17
- package/dist/market_adapter/lp_chart_core.js +1 -0
- package/dist/market_adapter/utils/chain.js +4 -3
- package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
- package/dist/market_adapter/utils/pair_orientation.js +142 -0
- package/dist/modules/account_bots.d.ts +40 -3
- package/dist/modules/account_bots.js +80 -37
- package/dist/modules/account_orders.d.ts +4 -1
- package/dist/modules/account_orders.js +4 -1
- package/dist/modules/bitshares-native/resolvers.js +3 -3
- package/dist/modules/bitshares-native/subscriptions.js +1 -1
- package/dist/modules/bitshares_client.d.ts +12 -10
- package/dist/modules/bitshares_client.js +12 -10
- package/dist/modules/bot_defaults.d.ts +13 -2
- package/dist/modules/bot_defaults.js +31 -2
- package/dist/modules/bot_settings.js +6 -3
- package/dist/modules/chain_keys.d.ts +5 -1
- package/dist/modules/chain_keys.js +5 -1
- package/dist/modules/chain_orders.d.ts +6 -2
- package/dist/modules/chain_orders.js +6 -2
- package/dist/modules/constants.d.ts +11 -0
- package/dist/modules/constants.js +31 -1
- package/dist/modules/credit_runtime.d.ts +35 -5
- package/dist/modules/credit_runtime.js +219 -38
- package/dist/modules/dexbot_class.d.ts +22 -2
- package/dist/modules/dexbot_class.js +61 -21
- package/dist/modules/dexbot_cow_runtime.js +19 -18
- package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
- package/dist/modules/dexbot_fill_runtime.js +4 -7
- package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
- package/dist/modules/dexbot_maintenance_runtime.js +52 -7
- package/dist/modules/dexbot_startup_runtime.js +3 -2
- package/dist/modules/dexbot_state_recovery.js +1 -1
- package/dist/modules/graceful_shutdown.d.ts +6 -2
- package/dist/modules/graceful_shutdown.js +6 -2
- package/dist/modules/launcher/bot_supervisor.js +4 -0
- package/dist/modules/launcher/launch_modes.js +6 -3
- package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
- package/dist/modules/launcher/monolithic_runtime.js +60 -1
- package/dist/modules/launcher/runtime_mode.d.ts +79 -0
- package/dist/modules/launcher/runtime_mode.js +223 -0
- package/dist/modules/market_adapter_whitelist.d.ts +8 -0
- package/dist/modules/market_adapter_whitelist.js +8 -0
- package/dist/modules/order/accounting.d.ts +15 -1
- package/dist/modules/order/accounting.js +15 -1
- package/dist/modules/order/async_lock.d.ts +9 -3
- package/dist/modules/order/async_lock.js +9 -3
- package/dist/modules/order/export.d.ts +0 -5
- package/dist/modules/order/export.js +2 -7
- package/dist/modules/order/format.d.ts +6 -4
- package/dist/modules/order/format.js +6 -4
- package/dist/modules/order/grid.d.ts +147 -19
- package/dist/modules/order/grid.js +321 -68
- package/dist/modules/order/grid_reconcile.js +4 -3
- package/dist/modules/order/grid_reconcile_internal.js +13 -18
- package/dist/modules/order/index.d.ts +4 -2
- package/dist/modules/order/index.js +1 -1
- package/dist/modules/order/logger_state.d.ts +1 -1
- package/dist/modules/order/logger_state.js +1 -1
- package/dist/modules/order/manager.d.ts +1 -0
- package/dist/modules/order/manager.js +5 -14
- package/dist/modules/order/sync_engine.d.ts +26 -11
- package/dist/modules/order/sync_engine.js +44 -20
- package/dist/modules/order/utils/math.d.ts +157 -47
- package/dist/modules/order/utils/math.js +236 -78
- package/dist/modules/order/utils/order.d.ts +64 -20
- package/dist/modules/order/utils/order.js +80 -24
- package/dist/modules/order/utils/system.d.ts +41 -11
- package/dist/modules/order/utils/system.js +43 -13
- package/dist/modules/order/utils/validate.d.ts +6 -3
- package/dist/modules/order/utils/validate.js +53 -60
- package/dist/modules/types.d.ts +7 -0
- package/dist/modules/utils/asset_symbols.d.ts +5 -5
- package/dist/modules/utils/asset_symbols.js +5 -5
- package/dist/modules/utils/errors.d.ts +2 -1
- package/dist/modules/utils/errors.js +2 -1
- package/dist/scripts/analyze-credit.js +44 -27
- package/dist/scripts/diagnose-pool-history.js +35 -30
- package/dist/scripts/pnl.js +1 -1
- package/dist/scripts/rich_list.d.ts +50 -0
- package/dist/scripts/rich_list.js +469 -0
- package/dist/scripts/run-tests.js +80 -4
- package/dist/unlock.d.ts +2 -1
- package/dist/unlock.js +53 -21
- package/docs/BITSHARES_ONBOARDING.md +7 -0
- package/docs/COW_INVARIANTS.md +7 -1
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +11 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
- package/docs/GRID_RECALCULATION.md +18 -6
- package/docs/LIFECYCLE.md +8 -8
- package/docs/LOGGING.md +16 -1
- package/docs/MPA_CREDIT_USAGE.md +10 -5
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +6 -5
- package/docs/architecture.md +56 -2
- package/docs/developer_guide.md +5 -1
- package/market_adapter/README.md +14 -7
- package/modules/README.md +1 -1
- package/package.json +4 -1
- package/scripts/README.md +59 -32
- package/tests/README.md +40 -2
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
|
|
34
34
|
* 2. grid.ts - Grid class (grid creation, synchronization, health)
|
|
35
35
|
* 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
|
|
36
|
-
* 4. format.ts - Numeric formatting (
|
|
36
|
+
* 4. format.ts - Numeric formatting (17 functions for consistent display)
|
|
37
37
|
* 5. accounting.ts - Accountant class (fund calculations and reconciliation)
|
|
38
38
|
* 6. logger.ts - Logger class (structured, color-coded output)
|
|
39
39
|
* 7. async_lock.ts - AsyncLock class (race condition prevention)
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* - Maintain audit trail for debugging
|
|
17
17
|
*
|
|
18
18
|
* ===============================================================================
|
|
19
|
-
* TABLE OF CONTENTS - LoggerState Class (
|
|
19
|
+
* TABLE OF CONTENTS - LoggerState Class (3 methods)
|
|
20
20
|
* ===============================================================================
|
|
21
21
|
*
|
|
22
22
|
* INITIALIZATION (1 method)
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* - Maintain audit trail for debugging
|
|
18
18
|
*
|
|
19
19
|
* ===============================================================================
|
|
20
|
-
* TABLE OF CONTENTS - LoggerState Class (
|
|
20
|
+
* TABLE OF CONTENTS - LoggerState Class (3 methods)
|
|
21
21
|
* ===============================================================================
|
|
22
22
|
*
|
|
23
23
|
* INITIALIZATION (1 method)
|
|
@@ -768,6 +768,7 @@ declare class OrderManager implements OrderManagerLike {
|
|
|
768
768
|
ordersPlaced: number;
|
|
769
769
|
partialsMoved: number;
|
|
770
770
|
stall?: import("../types.js").SpreadCorrectionStall;
|
|
771
|
+
transient?: boolean;
|
|
771
772
|
}>;
|
|
772
773
|
/**
|
|
773
774
|
* @param {Function} batchCb - Batch callback
|
|
@@ -27,7 +27,7 @@ import SyncEngine from './sync_engine.js';
|
|
|
27
27
|
import { calculateCurrentSpread, checkSpreadCondition, checkGridHealth } from './grid.js';
|
|
28
28
|
import * as Format from './format.js';
|
|
29
29
|
import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELINE_TIMING, COW_PERFORMANCE, COW_ACTIONS, GRID_LIMITS } from '../constants.js';
|
|
30
|
-
import { seedBotRuntimeConfig } from '../bot_defaults.js';
|
|
30
|
+
import { seedBotRuntimeConfig, createDefaultBotMetrics } from '../bot_defaults.js';
|
|
31
31
|
import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
|
|
32
32
|
import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
|
|
33
33
|
import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
|
|
@@ -599,24 +599,15 @@ class OrderManager {
|
|
|
599
599
|
this._lastBoundaryHoldResyncAt = 0;
|
|
600
600
|
this._gapEvacStreaks = new Map();
|
|
601
601
|
this._gapEvacCancelQueued = new Set();
|
|
602
|
+
// Shared counters come from the central factory (createDefaultBotMetrics);
|
|
603
|
+
// the manager-owned runtime counters are added on top.
|
|
602
604
|
this._metrics = {
|
|
603
|
-
|
|
604
|
-
batchesExecuted: 0,
|
|
605
|
-
fillProcessingTimeMs: 0,
|
|
606
|
-
lockContentionEvents: 0,
|
|
607
|
-
maxQueueDepth: 0,
|
|
608
|
-
fundRecalcCount: 0,
|
|
605
|
+
...createDefaultBotMetrics(),
|
|
609
606
|
lockAcquisitions: 0,
|
|
610
607
|
lockContentionSkips: 0,
|
|
611
|
-
gridLockContention: 0,
|
|
612
608
|
spreadRoleConversionBlocked: 0,
|
|
613
609
|
lastSyncDurationMs: 0,
|
|
614
|
-
metricsStartTime: Date.now()
|
|
615
|
-
refusedCommitCount: 0,
|
|
616
|
-
orphanFillCreditedCount: 0,
|
|
617
|
-
restampBuyAboveAnchorCount: 0,
|
|
618
|
-
boundaryDriftExceedsWindowCount: 0,
|
|
619
|
-
gapBandPlacementShadowCount: 0
|
|
610
|
+
metricsStartTime: Date.now()
|
|
620
611
|
};
|
|
621
612
|
this._bootstrapping = 1;
|
|
622
613
|
this.logger?.log('[BOOTSTRAP] Started', 'debug');
|
|
@@ -15,12 +15,17 @@
|
|
|
15
15
|
* Uses AsyncLock to prevent concurrent sync operations (defense-in-depth locking).
|
|
16
16
|
*
|
|
17
17
|
* ===============================================================================
|
|
18
|
-
* TABLE OF CONTENTS - SyncEngine Class (
|
|
18
|
+
* TABLE OF CONTENTS - SyncEngine Class (12 methods) + module-level helpers
|
|
19
19
|
* ===============================================================================
|
|
20
20
|
*
|
|
21
|
-
* MODULE-LEVEL
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* MODULE-LEVEL HELPERS (internal, not exported):
|
|
22
|
+
* readSingleOrderSeam / batchReadOrdersSeam - Chain-order read indirection seams
|
|
23
|
+
* confirmSuspectEmptyRead(mgr) - Re-read after a suspicious empty snapshot
|
|
24
|
+
* describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedIds) -
|
|
25
|
+
* Diagnostic candidates for nearest-slot adoption
|
|
26
|
+
* chainPriceOnSameLevel(...) - Chain price vs a grid level under precision rules
|
|
27
|
+
* adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) - Adoption guard
|
|
28
|
+
* adoptChainOrderIntoSlot(...) - Adopt an unmatched chain order into a free slot
|
|
24
29
|
*
|
|
25
30
|
* INITIALIZATION (1 method)
|
|
26
31
|
* 1. constructor(manager) - Create new SyncEngine with manager reference
|
|
@@ -39,30 +44,40 @@
|
|
|
39
44
|
* Pass 1: Match grid orders to chain (known grid → chain, includes orphan cleanup)
|
|
40
45
|
* Pass 2: Add missing chain orders (unknown chain → grid)
|
|
41
46
|
*
|
|
42
|
-
* FILL PROCESSING (
|
|
43
|
-
* 5.
|
|
47
|
+
* FILL PROCESSING (5 methods)
|
|
48
|
+
* 5. _findMatchingGridOrder(mgr, orderId) - Look up the grid slot owning a chain order (internal)
|
|
49
|
+
*
|
|
50
|
+
* 6. _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) -
|
|
51
|
+
* Resolve the asset/side context for a fill (internal)
|
|
52
|
+
*
|
|
53
|
+
* 7. _computeFillTransitionResult(mgr, params) - Compute the post-fill slot
|
|
54
|
+
* transition and fund deltas without mutating state (internal, async)
|
|
55
|
+
*
|
|
56
|
+
* 8. syncFromFillHistory(fill) - Process single fill event synchronously
|
|
44
57
|
* Updates grid order state based on fill data
|
|
45
58
|
* Updates fund state and accounting
|
|
46
59
|
* Handles both maker and taker fills
|
|
47
60
|
*
|
|
48
|
-
*
|
|
61
|
+
* 9. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
|
|
49
62
|
* Acquires _gridLock once for all fills in block group
|
|
50
63
|
* Batches drift refetch into one get_objects RPC call
|
|
51
64
|
* Applies all grid mutations in a single applyGridUpdateBatch
|
|
52
65
|
*
|
|
53
|
-
* FULL SYNCHRONIZATION (
|
|
54
|
-
*
|
|
66
|
+
* FULL SYNCHRONIZATION (2 methods - async)
|
|
67
|
+
* 10. _assertGenesisInvariant(mgr) - Fail-closed check that a snapshot has a genesis ladder (internal)
|
|
68
|
+
*
|
|
69
|
+
* 11. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
|
|
55
70
|
* Fetches fresh account balances
|
|
56
71
|
* Calls syncFromOpenOrders() with chain data
|
|
57
72
|
* Source: event type that triggered sync (fill, poll, broadcast, etc.)
|
|
58
73
|
*
|
|
59
74
|
* ACCOUNT STATE (2 methods - async)
|
|
60
|
-
*
|
|
75
|
+
* 12. fetchAccountBalancesAndSetTotals() - Fetch account totals (async)
|
|
61
76
|
* Retrieves BUY/SELL totals and free balances from blockchain
|
|
62
77
|
* Sets manager.accountTotals
|
|
63
78
|
* Triggers fund recalculation
|
|
64
79
|
*
|
|
65
|
-
*
|
|
80
|
+
* 13. initializeAssets() - Initialize asset metadata (async)
|
|
66
81
|
* Fetches asset precision and other metadata
|
|
67
82
|
* Sets manager.assets
|
|
68
83
|
* Called once at bot startup
|
|
@@ -15,12 +15,17 @@
|
|
|
15
15
|
* Uses AsyncLock to prevent concurrent sync operations (defense-in-depth locking).
|
|
16
16
|
*
|
|
17
17
|
* ===============================================================================
|
|
18
|
-
* TABLE OF CONTENTS - SyncEngine Class (
|
|
18
|
+
* TABLE OF CONTENTS - SyncEngine Class (12 methods) + module-level helpers
|
|
19
19
|
* ===============================================================================
|
|
20
20
|
*
|
|
21
|
-
* MODULE-LEVEL
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* MODULE-LEVEL HELPERS (internal, not exported):
|
|
22
|
+
* readSingleOrderSeam / batchReadOrdersSeam - Chain-order read indirection seams
|
|
23
|
+
* confirmSuspectEmptyRead(mgr) - Re-read after a suspicious empty snapshot
|
|
24
|
+
* describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedIds) -
|
|
25
|
+
* Diagnostic candidates for nearest-slot adoption
|
|
26
|
+
* chainPriceOnSameLevel(...) - Chain price vs a grid level under precision rules
|
|
27
|
+
* adoptedSlotKeepsItsOwnPrice(mgr, adopted, chainOrderId, path) - Adoption guard
|
|
28
|
+
* adoptChainOrderIntoSlot(...) - Adopt an unmatched chain order into a free slot
|
|
24
29
|
*
|
|
25
30
|
* INITIALIZATION (1 method)
|
|
26
31
|
* 1. constructor(manager) - Create new SyncEngine with manager reference
|
|
@@ -39,30 +44,40 @@
|
|
|
39
44
|
* Pass 1: Match grid orders to chain (known grid → chain, includes orphan cleanup)
|
|
40
45
|
* Pass 2: Add missing chain orders (unknown chain → grid)
|
|
41
46
|
*
|
|
42
|
-
* FILL PROCESSING (
|
|
43
|
-
* 5.
|
|
47
|
+
* FILL PROCESSING (5 methods)
|
|
48
|
+
* 5. _findMatchingGridOrder(mgr, orderId) - Look up the grid slot owning a chain order (internal)
|
|
49
|
+
*
|
|
50
|
+
* 6. _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) -
|
|
51
|
+
* Resolve the asset/side context for a fill (internal)
|
|
52
|
+
*
|
|
53
|
+
* 7. _computeFillTransitionResult(mgr, params) - Compute the post-fill slot
|
|
54
|
+
* transition and fund deltas without mutating state (internal, async)
|
|
55
|
+
*
|
|
56
|
+
* 8. syncFromFillHistory(fill) - Process single fill event synchronously
|
|
44
57
|
* Updates grid order state based on fill data
|
|
45
58
|
* Updates fund state and accounting
|
|
46
59
|
* Handles both maker and taker fills
|
|
47
60
|
*
|
|
48
|
-
*
|
|
61
|
+
* 9. syncFromFillHistoryBatch(fills) - Process multiple fill events in batch
|
|
49
62
|
* Acquires _gridLock once for all fills in block group
|
|
50
63
|
* Batches drift refetch into one get_objects RPC call
|
|
51
64
|
* Applies all grid mutations in a single applyGridUpdateBatch
|
|
52
65
|
*
|
|
53
|
-
* FULL SYNCHRONIZATION (
|
|
54
|
-
*
|
|
66
|
+
* FULL SYNCHRONIZATION (2 methods - async)
|
|
67
|
+
* 10. _assertGenesisInvariant(mgr) - Fail-closed check that a snapshot has a genesis ladder (internal)
|
|
68
|
+
*
|
|
69
|
+
* 11. synchronizeWithChain(chainData, source) - Full sync (fetch + sync) (async)
|
|
55
70
|
* Fetches fresh account balances
|
|
56
71
|
* Calls syncFromOpenOrders() with chain data
|
|
57
72
|
* Source: event type that triggered sync (fill, poll, broadcast, etc.)
|
|
58
73
|
*
|
|
59
74
|
* ACCOUNT STATE (2 methods - async)
|
|
60
|
-
*
|
|
75
|
+
* 12. fetchAccountBalancesAndSetTotals() - Fetch account totals (async)
|
|
61
76
|
* Retrieves BUY/SELL totals and free balances from blockchain
|
|
62
77
|
* Sets manager.accountTotals
|
|
63
78
|
* Triggers fund recalculation
|
|
64
79
|
*
|
|
65
|
-
*
|
|
80
|
+
* 13. initializeAssets() - Initialize asset metadata (async)
|
|
66
81
|
* Fetches asset precision and other metadata
|
|
67
82
|
* Sets manager.assets
|
|
68
83
|
* Called once at bot startup
|
|
@@ -123,7 +138,7 @@ function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
|
|
|
123
138
|
const { BitShares } = client;
|
|
124
139
|
import { NATIVE_CLIENT } from '../constants.js';
|
|
125
140
|
const { toFiniteNumber } = Format;
|
|
126
|
-
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual } from './utils/math.js';
|
|
141
|
+
import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
|
|
127
142
|
import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
|
|
128
143
|
import { parseSlotIndex } from './utils/slot.js';
|
|
129
144
|
import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
|
|
@@ -228,7 +243,7 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
|
|
|
228
243
|
const priceDiff = Math.abs(price - chainPrice);
|
|
229
244
|
let priceEqual = false;
|
|
230
245
|
try {
|
|
231
|
-
priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision);
|
|
246
|
+
priceEqual = chainPriceOnSameLevel(chainPrice, price, mgr?._genesis, precision, mgr?.assets, chainSize, toFiniteNumber(slot.size), chainOrder.type, mgr?.config?.incrementPercent);
|
|
232
247
|
}
|
|
233
248
|
catch {
|
|
234
249
|
priceEqual = chainPrice === price;
|
|
@@ -293,13 +308,20 @@ function describeNearestAdoptionCandidates(mgr, chainOrder, precision, matchedGr
|
|
|
293
308
|
* correction / duplicate / re-slot warranted. Unjudgeable inputs (no ladder,
|
|
294
309
|
* non-finite price) fall back to integer equality at the asset precision.
|
|
295
310
|
*/
|
|
296
|
-
function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision) {
|
|
311
|
+
function chainPriceOnSameLevel(chainPrice, slotPrice, genesis, precision, assets = null, chainSize = 0, slotSize = 0, type = null, incrementPercent = null) {
|
|
297
312
|
if (hasGenesisLadder(genesis)) {
|
|
298
313
|
try {
|
|
299
314
|
const g = genesis;
|
|
300
315
|
return slotIndexForPrice(chainPrice, g) === slotIndexForPrice(slotPrice, g);
|
|
301
316
|
}
|
|
302
|
-
catch { /* unjudgeable — fall through to
|
|
317
|
+
catch { /* unjudgeable — fall through to price-level comparison */ }
|
|
318
|
+
}
|
|
319
|
+
// No ladder (legacy/migration window): compare the chain price to the slot
|
|
320
|
+
// price with the chain-representable tolerance, capped to half a grid step.
|
|
321
|
+
// NOT priceSlotEqual at the asset amount precision, which collapses
|
|
322
|
+
// adjacent levels for a low-precision asset.
|
|
323
|
+
if (assets != null) {
|
|
324
|
+
return pricesOnSameLevel(chainPrice, chainSize, type, slotPrice, slotSize, type, assets, incrementPercent);
|
|
303
325
|
}
|
|
304
326
|
try {
|
|
305
327
|
return priceSlotEqual(chainPrice, slotPrice, precision);
|
|
@@ -975,7 +997,7 @@ class SyncEngine {
|
|
|
975
997
|
// drift of a few quanta inside one level is normal and must
|
|
976
998
|
// not queue a price correction.
|
|
977
999
|
const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
|
|
978
|
-
const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision);
|
|
1000
|
+
const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(chainOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent);
|
|
979
1001
|
if (!isPriceEqual) {
|
|
980
1002
|
queueCorrection({
|
|
981
1003
|
gridOrder: { ...gridOrder },
|
|
@@ -1017,7 +1039,7 @@ class SyncEngine {
|
|
|
1017
1039
|
// ladder level as the slot (the swap tiebreak's whole
|
|
1018
1040
|
// premise — a duplicate at this level).
|
|
1019
1041
|
const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
|
|
1020
|
-
if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision))
|
|
1042
|
+
if (!chainPriceOnSameLevel(candidateOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(candidateOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent))
|
|
1021
1043
|
continue;
|
|
1022
1044
|
if (floatToBlockchainInt(candidateOrder.size, precision) !== currentSizeInt)
|
|
1023
1045
|
continue;
|
|
@@ -1231,8 +1253,7 @@ class SyncEngine {
|
|
|
1231
1253
|
// (no adopt, no cancelOnly), e.g. dip-protection levels
|
|
1232
1254
|
// sitting below a fresh grid after a reset.
|
|
1233
1255
|
{
|
|
1234
|
-
|
|
1235
|
-
if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, precision)) {
|
|
1256
|
+
if (isChainPriceOutOfGrid(chainOrder.price, genesisLadder, toFiniteNumber(chainOrder.size), chainOrder.type, mgr.assets)) {
|
|
1236
1257
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'out-of-grid-deferred', candidateSlotId: slotId });
|
|
1237
1258
|
mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: price outside grid range, deferred (nearest slot ${slotId})`, 'warn');
|
|
1238
1259
|
continue;
|
|
@@ -1248,7 +1269,10 @@ class SyncEngine {
|
|
|
1248
1269
|
// legitimate in-rail orphan waits one sync cycle
|
|
1249
1270
|
// post-boundary-commit before adoption. Strictly better than
|
|
1250
1271
|
// adopting a gap stray into the wrong slot.
|
|
1251
|
-
|
|
1272
|
+
// '' guard: Number('') === 0 is finite, so an empty-string
|
|
1273
|
+
// boundary would read as boundary 0 (same trap guarded in
|
|
1274
|
+
// runPreBroadcastGuards / resolveGapBand).
|
|
1275
|
+
if (boundaryIdx == null || boundaryIdx === '' || !Number.isFinite(Number(boundaryIdx))) {
|
|
1252
1276
|
unmatchedChainOrders.push({ chainOrderId, type: chainOrder.type, price: chainOrder.price, size: chainOrder.size, raw: rawChainOrders.get(chainOrderId), reason: 'boundary-unknown-deferred', candidateSlotId: slotId });
|
|
1253
1277
|
mgr.logger?.log?.(`[SYNC] Orphaned chain order ${chainOrderId} (${chainOrder.type}, price=${chainOrder.price}, size=${chainOrder.size}) — NOT adopted: boundary unknown, deferred until boundary commits (nearest slot ${slotId})`, 'warn');
|
|
1254
1278
|
continue;
|
|
@@ -4,56 +4,93 @@
|
|
|
4
4
|
* Pure numeric calculations, blockchain conversions, fee math, and fund allocation.
|
|
5
5
|
*
|
|
6
6
|
* ===============================================================================
|
|
7
|
-
* TABLE OF CONTENTS (
|
|
7
|
+
* TABLE OF CONTENTS (78 exports)
|
|
8
8
|
* ===============================================================================
|
|
9
9
|
*
|
|
10
|
-
* SECTION 1:
|
|
10
|
+
* SECTION 1: GENESIS LADDER & RAIL GEOMETRY (28 items)
|
|
11
|
+
* - GridGenesis - Genesis ladder type: start price, increment, gap slots,
|
|
12
|
+
* price levels and their hash
|
|
13
|
+
* - priceLevelsForGenesis(genesis) - Extract the frozen price ladder from a genesis
|
|
14
|
+
* - buildGenesisFromPriceLevels(levels, config) - Build a genesis from precomputed levels
|
|
15
|
+
* - derivePriceLevels(startPrice, increment, minPrice, maxPrice) - Derive the
|
|
16
|
+
* geometric price ladder (the "rail") from a live config
|
|
17
|
+
* - hashPriceLevels(levels) - Deterministic hash of a price ladder
|
|
18
|
+
* - priceForSlot(idx, genesis) - Authoritative price for a slot index
|
|
19
|
+
* - slotIndexForPrice(price, genesis) - Resolve a price to its slot index
|
|
20
|
+
* - slotIdForPrice(price, genesis) - Resolve a price to its "slot-N" id
|
|
21
|
+
* - assertSlotPriceInvariant(...) - Reject a slot whose price disagrees with its index
|
|
22
|
+
* - priceSlotEqual(...) - Compare slot/price pairs under the genesis invariant
|
|
23
|
+
* - sameGridLevel(a, b) - Same ladder level, resolving each price against its genesis
|
|
24
|
+
* - sameGridPrice(a, b) - Same genesis-derived ladder level by precision
|
|
25
|
+
* - pricesOnSameLevel(a, b, ...) - Same order-book price LEVEL under precision
|
|
26
|
+
* - isChainPriceOutOfGrid(price, genesis, ...) - Whether a chain price is off the rail
|
|
27
|
+
* - getBtsSide(assets) - Which side of the pair holds BTS
|
|
28
|
+
* - getSellStartIdx(boundaryIdx, gapSlots) - Sell start index from boundary + gap
|
|
29
|
+
* - calculateGapSlots(incrementPercent, targetSpreadPercent) - Gap-slot count
|
|
30
|
+
* - resolveGapSlots(manager) - Configured gap-slot count for a manager
|
|
31
|
+
* - resolveGapBand(manager) - Gap-band geometry { start, end, gapSlots }
|
|
32
|
+
* - countGapBandSpread(manager) - Count SPREAD slots strictly inside the gap band
|
|
33
|
+
* - isSlotInRail(...) - Geometric rail-membership test for a slot
|
|
34
|
+
* - isSlotIndexInGapBand(idx, ...) - Whether a slot index sits inside the gap band
|
|
35
|
+
* - isEvacuationRotationAllowed(...) - Whether a gap-evacuation rotation is geometrically valid
|
|
36
|
+
* - isEvacuationSizeStillValid(...) - Re-proof a stamped evacuation size against live geometry
|
|
37
|
+
* - validateBoundaryCommit(...) - Validate a proposed boundary commit against geometry
|
|
38
|
+
* - validatePersistedBoundary(...) - Validate a boundary restored from disk
|
|
39
|
+
* - isTransientInBandRejection(reason) - Whether a persisted-boundary rejection is transient
|
|
40
|
+
* - BOUNDARY_REJECT_PLACED_IN_BAND - Rejection reason: target slot holds an in-band order
|
|
41
|
+
*
|
|
42
|
+
* SECTION 2: PARSING & VALIDATION (10 functions)
|
|
11
43
|
* - isExplicitZeroAllocation(value) - Check if value is explicitly zero
|
|
12
44
|
* - isPercentageString(v) - Check if value is percentage string
|
|
45
|
+
* - isPositiveNumber(value) - Check if value is a positive number
|
|
46
|
+
* - isPositiveNumberOrPercent(value) - Positive number or positive percentage string
|
|
47
|
+
* - isPositiveInt(value) - Check if value is a positive integer
|
|
13
48
|
* - parsePercentageString(v) - Parse percentage string to decimal
|
|
49
|
+
* - toDecimal(value) - Convert number/percentage/numeric string to a decimal
|
|
14
50
|
* - parseRelativeMultiplier(value) - Parse "3x" multiplier syntax to number
|
|
15
51
|
* - resolveRelativePrice(value, startPrice, mode) - Resolve relative price values
|
|
16
52
|
* - validateGridPriceBounds(min, max, center) - Reject bounds not bracketing center
|
|
17
53
|
*
|
|
18
|
-
* SECTION
|
|
54
|
+
* SECTION 3: FUND CALCULATIONS (8 functions)
|
|
19
55
|
* - computeChainFundTotals(accountTotals, committedChain) - Compute total funds
|
|
20
56
|
* - calculateAvailableFundsValue(side, accountTotals, funds, ...) - Calculate available funds
|
|
57
|
+
* - adjustBudgetForBtsFees(budget, btsFeeData, ...) - Reserve BTS fees from a side budget
|
|
58
|
+
* - getGridBestPrices(manager) - Best (highest) buy and best (lowest) sell price
|
|
21
59
|
* - calculateSpreadFromOrders(activeBuys, activeSells) - Calculate spread percentage
|
|
22
60
|
* - resolveConfigValue(value, total) - Resolve percentage or absolute config value
|
|
61
|
+
* - resolveConfigValueWithRegistry(value, total, registry) - Config value incl. shared-account funds
|
|
62
|
+
* - hasValidAccountTotals(accountTotals, checkFree) - Validate account totals structure
|
|
23
63
|
*
|
|
24
|
-
* SECTION
|
|
64
|
+
* SECTION 4: BLOCKCHAIN CONVERSIONS (6 functions)
|
|
25
65
|
* - blockchainToFloat(intValue, precision) - Convert blockchain int to float
|
|
26
66
|
* - floatToBlockchainInt(floatValue, precision) - Convert float to blockchain int
|
|
67
|
+
* - floorToBlockchainInt(floatValue, precision) - Convert float to int by flooring
|
|
27
68
|
* - quantizeFloat(value, precision) - Round float to blockchain precision
|
|
28
69
|
* - normalizeInt(value, precision) - Normalize int within precision bounds
|
|
29
|
-
* -
|
|
70
|
+
* - quantumForPrecision(precision) - Smallest representable unit for a precision
|
|
30
71
|
*
|
|
31
|
-
* SECTION
|
|
32
|
-
* - roundTo(value, factor) - Round to a factor
|
|
33
|
-
* - fixedTo(value, decimals) - Format to fixed decimal string
|
|
34
|
-
* - roundToDecimals(value, decimals) - Round to N decimal places
|
|
72
|
+
* SECTION 5: PRECISION UTILITIES (4 functions)
|
|
35
73
|
* - getPrecision(assets, orderType) - Get precision for order type
|
|
36
74
|
* - getPrecisionByOrderType(assets, orderType) - Alias for getPrecision
|
|
37
|
-
* - getPrecisionForSide(assets, side) - Get precision by side (buy/sell)
|
|
38
75
|
* - getPrecisionsForManager(manager) - Get both asset precisions
|
|
39
76
|
* - getPrecisionSlack(precision) - Calculate tolerance for precision
|
|
40
77
|
*
|
|
41
|
-
* SECTION
|
|
78
|
+
* SECTION 6: ORDER SIZE VALIDATION (8 functions)
|
|
42
79
|
* - calculatePriceTolerance(price, size, type, assets) - Calculate price match tolerance
|
|
80
|
+
* - findCrossedOrder(...) - Find an opposite-side order a placement would CROSS
|
|
43
81
|
* - validateOrderAmountsWithinLimits(amountToSell, minToReceive) - Validate order limits
|
|
44
|
-
* - getMinOrderSize(assets,
|
|
82
|
+
* - getMinOrderSize(orderType, assets, factor) - Get minimum order size
|
|
45
83
|
* - getDustThresholdFactor() - Get dust threshold multiplier
|
|
46
84
|
* - getSingleDustThreshold(idealSize, dustThresholdPercent) - Get single dust threshold
|
|
47
85
|
* - getDoubleDustThreshold(idealSize, dustThresholdPercent) - Get double dust threshold
|
|
48
|
-
* - getMinOrderSize(orderType, assets, factor) - Get minimum order size
|
|
49
86
|
* - validateOrderSize(manager, size, type, context) - Validate order size against minimums
|
|
50
87
|
*
|
|
51
|
-
* SECTION
|
|
88
|
+
* SECTION 7: FEE CALCULATIONS (3 functions)
|
|
52
89
|
* - getAssetFees(assetSymbol, assetAmount, isMaker) - Get fee info for asset
|
|
90
|
+
* - getAssetFeesSafe(assetSymbol, assetAmount, isMaker) - Fee info without throwing
|
|
53
91
|
* - _setFeeCache(cache) - Set internal fee cache (internal)
|
|
54
|
-
* - _getFeeCache() - Get internal fee cache (internal)
|
|
55
92
|
*
|
|
56
|
-
* SECTION
|
|
93
|
+
* SECTION 8: FUND ALLOCATION (6 functions)
|
|
57
94
|
* - allocateFundsByWeights(available, targetCount) - Allocate funds by weight
|
|
58
95
|
* - cloneWeightDistribution(weightDistribution, base) - Clone weight distribution safely
|
|
59
96
|
* - calculateOrderSizes(manager, orderType) - Calculate order sizes for placement
|
|
@@ -61,13 +98,14 @@
|
|
|
61
98
|
* - calculateGridSideDivergenceMetric(manager, orderType, threshold) - Calculate divergence
|
|
62
99
|
* - clamp(value, min, max) - Clamp a value between min and max bounds
|
|
63
100
|
*
|
|
64
|
-
* SECTION
|
|
101
|
+
* SECTION 9: FEE DEDUCTION (2 functions)
|
|
65
102
|
* - calculateOrderCreationFees(count, btsFeeData) - Calculate total creation fees
|
|
66
|
-
* - deductOrderFeesFromFunds(available, count, btsFeeData, btsSide) - Deduct fees from funds
|
|
67
103
|
* - calculateSwapInAmount(targetReceive, poolReserveOut, poolReserveIn) - AMM swap math
|
|
68
104
|
*
|
|
69
|
-
* SECTION
|
|
70
|
-
* -
|
|
105
|
+
* SECTION 10: FORMATTING (3 functions)
|
|
106
|
+
* - roundTo(value, factor) - Round to a factor
|
|
107
|
+
* - fixedTo(value, decimals) - Format to fixed decimal string
|
|
108
|
+
* - roundToDecimals(value, decimals) - Round to N decimal places
|
|
71
109
|
*
|
|
72
110
|
* ===============================================================================
|
|
73
111
|
*/
|
|
@@ -589,19 +627,76 @@ declare function getBtsSide(assetA: string | undefined, assetB: string | undefin
|
|
|
589
627
|
*/
|
|
590
628
|
declare function calculatePriceTolerance(gridPrice: unknown, orderSize: unknown, orderType: string, assets?: AssetPair | null): number | null;
|
|
591
629
|
/**
|
|
592
|
-
*
|
|
593
|
-
*
|
|
594
|
-
*
|
|
595
|
-
*
|
|
596
|
-
*
|
|
597
|
-
*
|
|
598
|
-
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
|
|
604
|
-
|
|
630
|
+
* Whether two prices denote the same order-book price LEVEL, using the
|
|
631
|
+
* chain-representable price tolerance derived from both assets' precisions and
|
|
632
|
+
* the order size(s).
|
|
633
|
+
*
|
|
634
|
+
* WHY NOT priceSlotEqual(priceA, priceB, assetPrecision): a price is not an
|
|
635
|
+
* asset AMOUNT. Rounding it through one asset's precision
|
|
636
|
+
* (floatToBlockchainInt) collapses an entire adjacent grid band whenever the
|
|
637
|
+
* OTHER asset has low precision -- e.g. with a precision-4 quote asset both
|
|
638
|
+
* 0.000318 and 0.000319 round to 3, so every BUY after the first looked like a
|
|
639
|
+
* duplicate. The real on-chain price resolution is roughly
|
|
640
|
+
* 10^-precision / orderSize, which is exactly what calculatePriceTolerance
|
|
641
|
+
* derives. Use this for every production "same price level" check.
|
|
642
|
+
*
|
|
643
|
+
* Both types are evaluated and the tighter tolerance is kept (most
|
|
644
|
+
* conservative): a buy-vs-sell comparison where either side uses a
|
|
645
|
+
* precision-0 asset can otherwise produce a tolerance wider than the grid
|
|
646
|
+
* increment and falsely collide adjacent levels.
|
|
647
|
+
*
|
|
648
|
+
* @param {number} priceA - First price
|
|
649
|
+
* @param {number} sizeA - First order size (same side as typeA)
|
|
650
|
+
* @param {string|null|undefined} typeA - First order type (ORDER_TYPES)
|
|
651
|
+
* @param {number} priceB - Second price
|
|
652
|
+
* @param {number} sizeB - Second order size (same side as typeB)
|
|
653
|
+
* @param {string|null|undefined} typeB - Second order type (ORDER_TYPES)
|
|
654
|
+
* @param {object|null} assets - Manager assets (assetA/assetB with precision)
|
|
655
|
+
* @param {number|null} [incrementPercent] - Grid increment; when supplied the
|
|
656
|
+
* tolerance is clamped to half a grid step so a dust-inflated
|
|
657
|
+
* (MIN_ORDER_SIZE_FACTOR floor) tolerance cannot merge adjacent levels.
|
|
658
|
+
* @returns {boolean} True when the two prices sit on the same level
|
|
659
|
+
*/
|
|
660
|
+
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;
|
|
661
|
+
/**
|
|
662
|
+
* Whether two GENESIS-derived grid prices denote the same ladder level by
|
|
663
|
+
* EXACT identity (with float-noise slack).
|
|
664
|
+
*
|
|
665
|
+
* Grid slot prices are frozen ladder values (bit-identical per level), so
|
|
666
|
+
* exact equality is the correct identity for a grid-vs-grid comparison.
|
|
667
|
+
* Deliberately NOT priceSlotEqual at the asset precision (collapses an
|
|
668
|
+
* adjacent band for a low-precision asset) and NOT the chain tolerance (which
|
|
669
|
+
* can exceed the grid increment and merge two legitimately adjacent levels).
|
|
670
|
+
* Prefer sameGridLevel(genesis) where a ladder is available: it maps a drifted
|
|
671
|
+
* price back to its nearest ladder level. Use pricesOnSameLevel instead when
|
|
672
|
+
* one side is a chain-derived price that may sit a few chain quanta off its
|
|
673
|
+
* level.
|
|
674
|
+
*
|
|
675
|
+
* @param {number} priceA - First grid price
|
|
676
|
+
* @param {number} priceB - Second grid price
|
|
677
|
+
* @returns {boolean} True when both are the same ladder level
|
|
678
|
+
*/
|
|
679
|
+
declare function sameGridPrice(priceA: number, priceB: number): boolean;
|
|
680
|
+
/**
|
|
681
|
+
* Whether two grid prices denote the same ladder level, resolving each price
|
|
682
|
+
* to its nearest level through the frozen genesis ladder when one is supplied.
|
|
683
|
+
* This is robust to a price that was chain-corrected / rounded a quantum off
|
|
684
|
+
* its level: slotIndexForPrice maps it back to the level it came from, while a
|
|
685
|
+
* price that genuinely moved to another level resolves to a different index.
|
|
686
|
+
*
|
|
687
|
+
* PRECONDITION / HARDENING: slotIndexForPrice CLAMPS an out-of-rail price onto
|
|
688
|
+
* the edge levels, so two distinct out-of-rail prices would otherwise resolve
|
|
689
|
+
* "equal". This helper therefore only uses slot identity when BOTH prices sit
|
|
690
|
+
* inside [levels[0], levels[N-1]]; otherwise it falls back to exact-level
|
|
691
|
+
* identity (sameGridPrice, with float-noise slack). Callers pass in-rail grid
|
|
692
|
+
* prices today, but the guard makes out-of-rail misuse safe.
|
|
693
|
+
*
|
|
694
|
+
* @param {number} priceA - First grid price
|
|
695
|
+
* @param {number} priceB - Second grid price
|
|
696
|
+
* @param {unknown} genesis - Frozen genesis ladder (`manager._genesis`)
|
|
697
|
+
* @returns {boolean} True when both prices resolve to the same ladder level
|
|
698
|
+
*/
|
|
699
|
+
declare function sameGridLevel(priceA: number, priceB: number, genesis: unknown): boolean;
|
|
605
700
|
/**
|
|
606
701
|
* Find an opposite-side order that a candidate placement would CROSS.
|
|
607
702
|
*
|
|
@@ -615,10 +710,9 @@ declare function findPriceCollision(items: Iterable<CollisionItem>, excludeId: s
|
|
|
615
710
|
* sell ladder was re-priced into marketable buys, triggering a fatal
|
|
616
711
|
* fund assertion).
|
|
617
712
|
*
|
|
618
|
-
* Unlike
|
|
619
|
-
*
|
|
620
|
-
*
|
|
621
|
-
* cancelled earlier in the same plan).
|
|
713
|
+
* Unlike a same-price check, this catches crossings at ANY price overlap and
|
|
714
|
+
* is intended for the re-pricing UPDATE / CREATE paths. The caller decides the
|
|
715
|
+
* exemption policy (e.g. crossed orders cancelled earlier in the same plan).
|
|
622
716
|
*
|
|
623
717
|
* @param {Iterable<any>} items - Candidate orders (e.g. manager.orders.values())
|
|
624
718
|
* @param {number} price - Candidate placement price
|
|
@@ -789,15 +883,24 @@ declare function calculateSwapInAmount(targetReceive: number, poolReserveOut: nu
|
|
|
789
883
|
*
|
|
790
884
|
* @param {number} incrementPercent - Grid increment percentage
|
|
791
885
|
* @param {number} targetSpreadPercent - Target spread percentage
|
|
792
|
-
* @param {Object}
|
|
886
|
+
* @param {Object} [gridLimits] - Grid limits constants (optional, uses defaults)
|
|
793
887
|
* @returns {number} Number of gap slots
|
|
794
888
|
*/
|
|
795
889
|
declare function calculateGapSlots(incrementPercent: number | undefined, targetSpreadPercent: number | undefined, gridLimits?: GridLimitsLike): number;
|
|
796
890
|
/**
|
|
797
891
|
* Calculate sell start index from boundary index and gap slots.
|
|
798
892
|
* sellStartIdx = boundaryIdx + gapSlots + 1
|
|
893
|
+
*
|
|
894
|
+
* Absent-aware: Number(null) === 0 and Number('') === 0 would read "no
|
|
895
|
+
* boundary" as boundary 0 and manufacture a SELL-rail start at gapSlots+1.
|
|
896
|
+
* Unknown geometry (null/undefined/'') returns NaN so any unguarded caller
|
|
897
|
+
* fails closed via Number.isFinite instead of silently rail-biasing slot 0.
|
|
898
|
+
* Every current caller guards first (resolveGapBand, isSlotInRail,
|
|
899
|
+
* isSlotIndexInGapBand, geometryTypeForSlotIndex, the COW stamp paths);
|
|
900
|
+
* this carries the same contract in the helper itself so a future caller
|
|
901
|
+
* cannot bypass it. A genuine 0 boundary still yields gapSlots + 1.
|
|
799
902
|
*/
|
|
800
|
-
declare function getSellStartIdx(boundaryIdx: number | null, gapSlots: number | null): number;
|
|
903
|
+
declare function getSellStartIdx(boundaryIdx: number | string | null | undefined, gapSlots: number | string | null | undefined): number;
|
|
801
904
|
/**
|
|
802
905
|
* Resolve the configured gap-slot count for a manager-like object.
|
|
803
906
|
* Single source of truth for the `_gapSlots ?? calculateGapSlots(config)`
|
|
@@ -930,7 +1033,7 @@ declare function validatePersistedBoundary(proposedBoundary: number | null | und
|
|
|
930
1033
|
* over 2-3 cycles, so a snapshot taken mid-evacuation (or stale by one
|
|
931
1034
|
* crawl, as in recovery-before-CREATE) legitimately reports this. Nuking
|
|
932
1035
|
* the snapshot for it discards the boundary progression, pending crawls,
|
|
933
|
-
* streaks and the queued evacuation — the exact sabotage loop seen in
|
|
1036
|
+
* streaks and the queued evacuation — the exact sabotage loop seen in <bot>
|
|
934
1037
|
* 2026-09-13 (GAP-EVAC flags slot-96, COW plans 96→116, stale snapshot with
|
|
935
1038
|
* slot-94 still stranded fails validation, structural resync wipes the
|
|
936
1039
|
* plan). All other reasons (ceiling/range/crossed-book/...) are structural
|
|
@@ -974,7 +1077,7 @@ declare function countGapBandSpread(manager: OrderManagerLike, orders: Iterable<
|
|
|
974
1077
|
* (grid_reconcile_internal.ts), and the COW divergence correction (system.ts).
|
|
975
1078
|
* Drift between those copies is what let a fund-driven boundary shift leave a
|
|
976
1079
|
* SPREAD GUARD-typed stray inside the gap as "closest to market" — collapsing
|
|
977
|
-
* the spread (
|
|
1080
|
+
* the spread (<bot>: boundary 107→110 left the sell rail parked at 111-130
|
|
978
1081
|
* with the bottom three, 111-113, inside the new spread gap; real spread 0.5%
|
|
979
1082
|
* vs the 2.0% target).
|
|
980
1083
|
*
|
|
@@ -1076,11 +1179,18 @@ declare function slotIdForPrice(price: number, genesis: GridGenesis): string;
|
|
|
1076
1179
|
* slotIndexForPrice clamps out-of-range prices onto the edge slots (0/N-1),
|
|
1077
1180
|
* so callers MUST check this before adopting or duplicate-matching: a
|
|
1078
1181
|
* below-grid buy is not slot-0 and an above-grid sell is not slot-(N-1).
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1082
|
-
|
|
1083
|
-
|
|
1182
|
+
* Only genuine float dust at the edge is excused; anything further out is
|
|
1183
|
+
* out-of-grid -> hold/defer, never adopt or cancel as a duplicate.
|
|
1184
|
+
*
|
|
1185
|
+
* The edge excuse is the chain-representable tolerance (pricesOnSameLevel),
|
|
1186
|
+
* clamped to half a ladder step. Deliberately NOT priceSlotEqual at the asset
|
|
1187
|
+
* precision: a price is not an amount, so a precision-4 asset rounds a whole
|
|
1188
|
+
* adjacent band below the rail onto the edge and wrongly classifies a
|
|
1189
|
+
* dip-protection level as in-grid (fail-open). When assets/type are missing,
|
|
1190
|
+
* only float noise at the edge is excused (exact-level identity), so an
|
|
1191
|
+
* unjudgeable outside price stays out-of-grid (fail-closed).
|
|
1192
|
+
*/
|
|
1193
|
+
declare function isChainPriceOutOfGrid(price: number, genesis: GridGenesis, size?: number, type?: string | null, assets?: AssetPair | null): boolean;
|
|
1084
1194
|
declare function assertSlotPriceInvariant(slot: unknown, genesis: GridGenesis): void;
|
|
1085
1195
|
declare function priceSlotEqual(a: number, b: number, precision: number): boolean;
|
|
1086
1196
|
/**
|
|
@@ -1106,7 +1216,7 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
|
|
|
1106
1216
|
declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
|
|
1107
1217
|
declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
|
|
1108
1218
|
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,
|
|
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 };
|
|
1110
1220
|
/**
|
|
1111
1221
|
* Round a value to a given factor.
|
|
1112
1222
|
* @param {number} value - Value to round
|