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
|
@@ -50,9 +50,9 @@ const require = createRequire(import.meta.url);
|
|
|
50
50
|
import { path } from '../../path_api.js';
|
|
51
51
|
import { getStorage } from '../../storage/index.js';
|
|
52
52
|
const storage = getStorage();
|
|
53
|
-
import { API_LIMITS, ORDER_TYPES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS } from '../../constants.js';
|
|
53
|
+
import { API_LIMITS, ORDER_TYPES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
|
|
54
54
|
import { PATHS } from '../../paths.js';
|
|
55
|
-
import { toFiniteNumber, isValidNumber } from '../format.js';
|
|
55
|
+
import { toFiniteNumber, isValidNumber, toKnownNumber } from '../format.js';
|
|
56
56
|
import * as MathUtils from './math.js';
|
|
57
57
|
import * as OrderUtils from './order.js';
|
|
58
58
|
import Logger from '../../order/logger.js';
|
|
@@ -900,12 +900,15 @@ export async function persistGridSnapshot(manager, accountOrders, snapshotOrders
|
|
|
900
900
|
// treats as an explicit clear; the row carries the CURRENT live
|
|
901
901
|
// genesis hash so a restore that sees a re-derived genesis refuses it.
|
|
902
902
|
const lastFillPivot = buildLastFillPivotPayload(manager);
|
|
903
|
+
// Bot-scoped market-fill reference: survives grid regeneration, used
|
|
904
|
+
// by spread correction as the price it must not trade through.
|
|
905
|
+
const lastMarketFill = buildLastMarketFillPayload(manager);
|
|
903
906
|
await accountOrders.storeMasterGrid(orders, btsFeesOwed, manager.boundaryIdx, manager.assets || null, {
|
|
904
907
|
persistedAt: nowIso(),
|
|
905
908
|
config: debugConfig,
|
|
906
909
|
accountTotals,
|
|
907
910
|
btsBalance
|
|
908
|
-
}, fillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot);
|
|
911
|
+
}, fillKeys, genesis, gapEvacStreaks, pendingFillCrawls, lastFillPivot, lastMarketFill);
|
|
909
912
|
return true;
|
|
910
913
|
}
|
|
911
914
|
catch (e) {
|
|
@@ -977,36 +980,385 @@ function buildLastFillPivotPayload(manager) {
|
|
|
977
980
|
return { price, type, fillsAt, genesisHash };
|
|
978
981
|
}
|
|
979
982
|
/**
|
|
980
|
-
*
|
|
981
|
-
*
|
|
983
|
+
* Build the persist payload for the bot-scoped last-market-fill reference.
|
|
984
|
+
*
|
|
985
|
+
* Unlike buildLastFillPivotPayload this row has NO genesis binding and is
|
|
986
|
+
* never cleared by a grid regeneration/rejection: it records the last price
|
|
987
|
+
* the ACCOUNT traded at, which is market truth independent of the current
|
|
988
|
+
* grid. Returns `undefined` (storeMasterGrid no-op) while cold so a cold
|
|
989
|
+
* manager never erases a previously stored row; the restore path applies the
|
|
990
|
+
* TTL and drops an expired row instead.
|
|
991
|
+
*
|
|
992
|
+
* @param {Object} manager - OrderManager instance
|
|
993
|
+
* @returns {{price:number,type:string,fillsAt:number}|undefined} Row, or undefined to leave untouched
|
|
994
|
+
*/
|
|
995
|
+
function buildLastMarketFillPayload(manager) {
|
|
996
|
+
const price = Number(manager?._lastMarketFillPrice);
|
|
997
|
+
const type = manager?._lastMarketFillType;
|
|
998
|
+
const fillsAt = Number(manager?._lastMarketFillAt);
|
|
999
|
+
if (!Number.isFinite(price) || price <= 0)
|
|
1000
|
+
return undefined;
|
|
1001
|
+
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
1002
|
+
return undefined;
|
|
1003
|
+
if (!Number.isFinite(fillsAt) || fillsAt <= 0)
|
|
1004
|
+
return undefined;
|
|
1005
|
+
return { price, type, fillsAt };
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* The single freshness window shared by the spread-correction trust decisions
|
|
1009
|
+
* that are time-based: snapshot staleness (and therefore the COW bypass) and
|
|
1010
|
+
* the live-market-price refresh pacing. Resolved once so a per-bot
|
|
1011
|
+
* `config.timing` override cannot make one check trust what another rejects.
|
|
1012
|
+
* The crossing floor itself does NOT use a time window — it picks the newer
|
|
1013
|
+
* of the live read and the fill.
|
|
1014
|
+
*
|
|
1015
|
+
* 0 (constant unset) => no time bound: staleness never triggers and the
|
|
1016
|
+
* live-price refresh is never forced, so the crossing floor stays on the fill
|
|
1017
|
+
* anchor. Fail-open, matching the never-synced first-tick behavior.
|
|
1018
|
+
*
|
|
1019
|
+
* @param {Object} manager - OrderManager instance
|
|
1020
|
+
* @returns {number} Freshness window in ms (0 => no bound => fail-open)
|
|
1021
|
+
*/
|
|
1022
|
+
export function resolveSpreadFreshnessMs(manager) {
|
|
1023
|
+
const configured = Number(manager?.config?.timing?.SPREAD_CORRECTION_SYNC_FRESH_MS);
|
|
1024
|
+
if (configured > 0)
|
|
1025
|
+
return configured;
|
|
1026
|
+
const fallback = Number(TIMING?.SPREAD_CORRECTION_SYNC_FRESH_MS);
|
|
1027
|
+
return fallback > 0 ? fallback : 0;
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* Resolve the crossing floor spread correction must not trade through.
|
|
1031
|
+
*
|
|
1032
|
+
* Two pieces of real market evidence can supply the floor: an externally
|
|
1033
|
+
* observed live price (order book/ticker) and the fill-derived reference
|
|
1034
|
+
* (last account trade). Neither is judged by a threshold — the NEWER one wins.
|
|
1035
|
+
* A live read older than the last fill loses to the fill (an executed trade is
|
|
1036
|
+
* fresher market truth); a live read at least as new wins; with no live read
|
|
1037
|
+
* at all the fill is used; with neither the floor is null (fail-open).
|
|
1038
|
+
*
|
|
1039
|
+
* This is what lets us drop the arbitrary "how far is too far" distance cap:
|
|
1040
|
+
* we keep the floor fresh and compare evidence by recency, rather than guessing
|
|
1041
|
+
* when an old floor went stale.
|
|
1042
|
+
*
|
|
1043
|
+
* @param {Object} manager - OrderManager instance
|
|
1044
|
+
* @returns {number|null} Crossing floor or null (fail-open)
|
|
1045
|
+
*/
|
|
1046
|
+
export function resolveSpreadCrossingFloor(manager) {
|
|
1047
|
+
const fill = resolveSpreadMarketReference(manager);
|
|
1048
|
+
const live = Number(manager?._liveMarketPrice);
|
|
1049
|
+
const liveAt = Number(manager?._liveMarketPriceAt);
|
|
1050
|
+
const liveValid = Number.isFinite(live) && live > 0 && Number.isFinite(liveAt) && liveAt > 0;
|
|
1051
|
+
if (!liveValid)
|
|
1052
|
+
return fill;
|
|
1053
|
+
const fillAt = Math.max(Number(manager?._lastFilledAt) || 0, Number(manager?._lastMarketFillAt) || 0);
|
|
1054
|
+
if (fill == null || fillAt <= 0 || liveAt >= fillAt)
|
|
1055
|
+
return live;
|
|
1056
|
+
return fill;
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Refresh the cached live market price from the order book/ticker.
|
|
1060
|
+
* Best-effort; caches only a finite positive price. Returns the new price or
|
|
1061
|
+
* null. Call through maybeRefreshLiveMarketPrice to respect the pacing bound.
|
|
1062
|
+
*
|
|
1063
|
+
* @param {Object} manager - OrderManager instance
|
|
1064
|
+
* @param {unknown} BitShares - BitShares client
|
|
1065
|
+
* @returns {Promise<number|null>} New price or null
|
|
1066
|
+
*/
|
|
1067
|
+
export async function refreshLiveMarketPrice(manager, BitShares) {
|
|
1068
|
+
try {
|
|
1069
|
+
const symA = manager?.assets?.assetA?.symbol;
|
|
1070
|
+
const symB = manager?.assets?.assetB?.symbol;
|
|
1071
|
+
// Require a real client surface: tests and dry paths pass `{}` and must
|
|
1072
|
+
// not trigger (or await) a pointless lookup.
|
|
1073
|
+
const client = BitShares;
|
|
1074
|
+
if (!symA || !symB || !client || !client.db)
|
|
1075
|
+
return null;
|
|
1076
|
+
const raw = await deriveMarketPrice(client, symA, symB);
|
|
1077
|
+
const price = Number(raw);
|
|
1078
|
+
if (Number.isFinite(price) && price > 0) {
|
|
1079
|
+
manager._liveMarketPrice = price;
|
|
1080
|
+
manager._liveMarketPriceAt = Date.now();
|
|
1081
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Live market price refreshed ${price} (${symA}/${symB})`, 'debug');
|
|
1082
|
+
return price;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
catch { /* best-effort: fall back to the fill anchor */ }
|
|
1086
|
+
return null;
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Refresh the live market price if none is fresh, pacing attempts to one per
|
|
1090
|
+
* freshness window so a chain that keeps failing cannot turn the spread check
|
|
1091
|
+
* into an RPC loop. The spread path stays RPC-free while the cache is fresh.
|
|
1092
|
+
*
|
|
1093
|
+
* @param {Object} manager - OrderManager instance
|
|
1094
|
+
* @param {unknown} BitShares - BitShares client
|
|
1095
|
+
* @param {Object} [options]
|
|
1096
|
+
* @param {number} [options.now] - Injectable clock (tests)
|
|
1097
|
+
* @returns {Promise<number|null>} Cached/new price or null
|
|
1098
|
+
*/
|
|
1099
|
+
export async function maybeRefreshLiveMarketPrice(manager, BitShares, options = {}) {
|
|
1100
|
+
const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
|
|
1101
|
+
const freshMs = resolveSpreadFreshnessMs(manager);
|
|
1102
|
+
if (freshMs <= 0)
|
|
1103
|
+
return Number(manager?._liveMarketPrice) || null; // no bound => never force a read
|
|
1104
|
+
const liveAt = Number(manager?._liveMarketPriceAt);
|
|
1105
|
+
if (Number.isFinite(liveAt) && liveAt > 0 && (now - liveAt) <= freshMs) {
|
|
1106
|
+
return Number(manager?._liveMarketPrice) || null;
|
|
1107
|
+
}
|
|
1108
|
+
const attemptedAt = Number(manager?._liveMarketPriceAttemptedAt);
|
|
1109
|
+
if (Number.isFinite(attemptedAt) && attemptedAt > 0 && (now - attemptedAt) <= freshMs) {
|
|
1110
|
+
return null; // attempted recently; do not storm the chain
|
|
1111
|
+
}
|
|
1112
|
+
// No usable client surface: leave the floor on the fill anchor. Debug only
|
|
1113
|
+
// (expected for tests/dry paths) and paced like a real attempt so it cannot
|
|
1114
|
+
// fire on every tick.
|
|
1115
|
+
const client = BitShares;
|
|
1116
|
+
if (!client || !client.db) {
|
|
1117
|
+
manager._liveMarketPriceAttemptedAt = now;
|
|
1118
|
+
manager.logger?.log?.('[SPREAD-CORRECTION] Live market price refresh skipped: no order-book client; crossing floor stays on the fill anchor', 'debug');
|
|
1119
|
+
return null;
|
|
1120
|
+
}
|
|
1121
|
+
manager._liveMarketPriceAttemptedAt = now;
|
|
1122
|
+
const refreshed = await refreshLiveMarketPrice(manager, BitShares);
|
|
1123
|
+
if (refreshed == null) {
|
|
1124
|
+
// One warn per pacing window: a persistently failing order-book/ticker
|
|
1125
|
+
// read silently degrades the floor to the fill anchor otherwise.
|
|
1126
|
+
manager.logger?.log?.('[SPREAD-CORRECTION] Live market price refresh failed; crossing floor stays on the fill anchor until the next attempt', 'warn');
|
|
1127
|
+
}
|
|
1128
|
+
return refreshed;
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Evaluate whether spread correction may act on the current local snapshot,
|
|
1132
|
+
* in ONE place. Pure: reads manager state, returns a verdict, no side effects;
|
|
1133
|
+
* the caller maps the reason to a stall and the existing wiring arms the
|
|
1134
|
+
* targeted sync.
|
|
1135
|
+
*
|
|
1136
|
+
* Premises:
|
|
1137
|
+
* - P-A cold book (no live order on either side): `ok=false` — hard refusal,
|
|
1138
|
+
* there is no realized spread to repair and only the reconcile path owns
|
|
1139
|
+
* the first window. Requires `options.onChainOrders`; skipped otherwise.
|
|
1140
|
+
* - P-B stale snapshot (a completed sync is older than the freshness window):
|
|
1141
|
+
* degraded-ok — the planner may still act, but `snapshotTrusted=false` so
|
|
1142
|
+
* the LAST-FILL-GUARD bypass is withheld. Never-synced is treated as fresh
|
|
1143
|
+
* (historical fail-open for the first tick).
|
|
1144
|
+
* - P-C known-unmatched chain orders: degraded-ok — plan, but the collision
|
|
1145
|
+
* filter drops their price levels and `snapshotTrusted=false`.
|
|
1146
|
+
*
|
|
1147
|
+
* The market anchor is deliberately NOT a refusal premise — it is returned for
|
|
1148
|
+
* the crossing filter, and a real fill denies the bypass via `fillMarketRef`.
|
|
1149
|
+
*
|
|
1150
|
+
* @param {Object} manager - OrderManager instance
|
|
1151
|
+
* @param {Object} [options]
|
|
1152
|
+
* @param {number} [options.now] - Injectable clock (tests)
|
|
1153
|
+
* @param {Object|null} [options.onChainOrders] - Live local window view; enables P-A
|
|
1154
|
+
* @returns {SpreadCorrectionReadiness} Readiness verdict
|
|
1155
|
+
*/
|
|
1156
|
+
export function evaluateSpreadCorrectionReadiness(manager, options = {}) {
|
|
1157
|
+
// The gate must never throw into the planner or the bypass check: a failure
|
|
1158
|
+
// is caught and turned into a refusal (correct-by-refusal), not a plan with
|
|
1159
|
+
// no floor. Callers surface it as the 'readiness-gate' stall.
|
|
1160
|
+
try {
|
|
1161
|
+
const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
|
|
1162
|
+
const freshMs = resolveSpreadFreshnessMs(manager);
|
|
1163
|
+
const marketRef = resolveSpreadCrossingFloor(manager);
|
|
1164
|
+
const fillMarketRef = resolveSpreadMarketReference(manager);
|
|
1165
|
+
const unmatched = Array.isArray(manager?._lastUnmatchedChainOrders)
|
|
1166
|
+
? manager._lastUnmatchedChainOrders
|
|
1167
|
+
: [];
|
|
1168
|
+
const synced = Number.isFinite(Number(manager?._lastSyncAt)) && Number(manager?._lastSyncAt) > 0;
|
|
1169
|
+
// Never-synced, or no usable window => fresh (fail-open for the first tick).
|
|
1170
|
+
const stale = synced && freshMs > 0 && (now - Number(manager?._lastSyncAt) > freshMs);
|
|
1171
|
+
const cold = !!options?.onChainOrders
|
|
1172
|
+
&& options.onChainOrders.buys.length === 0
|
|
1173
|
+
&& options.onChainOrders.sells.length === 0;
|
|
1174
|
+
const unmatchedPresent = unmatched.length > 0;
|
|
1175
|
+
let reason = null;
|
|
1176
|
+
if (cold)
|
|
1177
|
+
reason = 'cold-book';
|
|
1178
|
+
else if (stale)
|
|
1179
|
+
reason = 'stale-snapshot';
|
|
1180
|
+
else if (unmatchedPresent)
|
|
1181
|
+
reason = 'unmatched-orders';
|
|
1182
|
+
return {
|
|
1183
|
+
ok: !cold,
|
|
1184
|
+
reason,
|
|
1185
|
+
marketRef,
|
|
1186
|
+
fillMarketRef,
|
|
1187
|
+
snapshotTrusted: !stale && !unmatchedPresent,
|
|
1188
|
+
unmatched,
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
catch (err) {
|
|
1192
|
+
// Correct-by-refusal: a gate that cannot read state refuses the cycle.
|
|
1193
|
+
// reason stays null (the cause is not a real premise, it is a fault);
|
|
1194
|
+
// callers map null to the 'readiness-gate' stall so the targeted sync
|
|
1195
|
+
// arms and triage logs name the fault. Detail-only log: the caller owns
|
|
1196
|
+
// the operator warning, so a gate-failure cycle is reported once.
|
|
1197
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Readiness gate failed (${getErrorMessage(err)}); refusing the cycle`, 'debug');
|
|
1198
|
+
return { ok: false, reason: null, marketRef: null, fillMarketRef: null, snapshotTrusted: false, unmatched: [] };
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Resolve the last real FILL price — the fill-derived market reference.
|
|
1203
|
+
* Returns null (fail-open) when no real fill is known.
|
|
1204
|
+
*
|
|
1205
|
+
* The bot's grid anchor (AMA/startPrice) and its own book mid are NOT market
|
|
1206
|
+
* references — they are grid geometry or the bot's own quotes — so they are
|
|
1207
|
+
* deliberately not used here. Only a real fill price qualifies: the live
|
|
1208
|
+
* LAST-FILL-GUARD pivot when it is fill-provenanced, else the bot-scoped
|
|
1209
|
+
* persisted reference that survives grid regeneration.
|
|
1210
|
+
*
|
|
1211
|
+
* Feeds the COW bypass gate (via the readiness verdict's `fillMarketRef`) and
|
|
1212
|
+
* is the fallback crossing floor when no fresh live market read exists.
|
|
1213
|
+
*
|
|
1214
|
+
* @param {Object} manager - OrderManager instance
|
|
1215
|
+
* @returns {number|null} Reference price or null
|
|
1216
|
+
*/
|
|
1217
|
+
export function resolveSpreadMarketReference(manager) {
|
|
1218
|
+
const live = Number(manager?._lastFilledPrice);
|
|
1219
|
+
const liveType = manager?._lastFilledType;
|
|
1220
|
+
if (manager?.lastFillPivotSource === 'fill' && Number.isFinite(live) && live > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
|
|
1221
|
+
return live;
|
|
1222
|
+
}
|
|
1223
|
+
const market = Number(manager?._lastMarketFillPrice);
|
|
1224
|
+
const marketType = manager?._lastMarketFillType;
|
|
1225
|
+
if (Number.isFinite(market) && market > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
|
|
1226
|
+
return market;
|
|
1227
|
+
}
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Resolve the reference the generic LAST-FILL-GUARD judges against.
|
|
1232
|
+
*
|
|
1233
|
+
* Prefers the live armed pivot. When that is cold (a grid regeneration
|
|
1234
|
+
* cleared it, or a rejected-snapshot reset ran) it falls back to the
|
|
1235
|
+
* bot-scoped last-market-fill row — the same market truth spread correction
|
|
1236
|
+
* already uses. This is what stops a rebuild from silently un-arming the
|
|
1237
|
+
* guard until the next fill: the price the account last traded at is known,
|
|
1238
|
+
* so a CREATE/rotation must still not cross it.
|
|
1239
|
+
*
|
|
1240
|
+
* Read-time fallback only: it does NOT mutate the pivot or persist an
|
|
1241
|
+
* old-generation value, so the genesis-bound pivot/persist contract is
|
|
1242
|
+
* unchanged. The guard still validates the value onto the CURRENT ladder via
|
|
1243
|
+
* resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
|
|
1244
|
+
* regenerated geometry stays the authority on which placements are off-grid.
|
|
1245
|
+
*
|
|
1246
|
+
* @param {Object} manager - OrderManager instance
|
|
1247
|
+
* @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
|
|
1248
|
+
*/
|
|
1249
|
+
export function resolveLastFillGuardReference(manager) {
|
|
1250
|
+
const livePrice = Number(manager?._lastFilledPrice);
|
|
1251
|
+
const liveType = manager?._lastFilledType;
|
|
1252
|
+
if (Number.isFinite(livePrice) && livePrice > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
|
|
1253
|
+
return { price: livePrice, type: liveType };
|
|
1254
|
+
}
|
|
1255
|
+
const marketPrice = Number(manager?._lastMarketFillPrice);
|
|
1256
|
+
const marketType = manager?._lastMarketFillType;
|
|
1257
|
+
if (Number.isFinite(marketPrice) && marketPrice > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
|
|
1258
|
+
return { price: marketPrice, type: marketType };
|
|
1259
|
+
}
|
|
1260
|
+
return { price: null, type: null };
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
* Restore the persisted bot-scoped last-market-fill reference into the
|
|
1264
|
+
* manager. Deliberately independent of the boundary and the genesis: this is
|
|
1265
|
+
* the anchor spread correction uses to avoid trading through the last real
|
|
1266
|
+
* fill price, and it must survive a grid regeneration (the genesis-bound
|
|
1267
|
+
* LAST-FILL-GUARD pivot does not). TTL-expired rows are erased from disk,
|
|
1268
|
+
* mirroring restoreLastFillPivot's dead-row hygiene.
|
|
982
1269
|
*
|
|
983
|
-
*
|
|
984
|
-
*
|
|
985
|
-
*
|
|
986
|
-
*
|
|
987
|
-
*
|
|
988
|
-
|
|
1270
|
+
* @param {Object} manager - OrderManager instance
|
|
1271
|
+
* @param {unknown} persisted - {price, type, fillsAt} from loadLastMarketFill
|
|
1272
|
+
* @param {Object} [options]
|
|
1273
|
+
* @param {number} [options.now] - Injectable clock (tests)
|
|
1274
|
+
* @returns {boolean} True when the reference was restored
|
|
1275
|
+
*/
|
|
1276
|
+
export function restoreLastMarketFill(manager, persisted, options = {}) {
|
|
1277
|
+
if (!manager)
|
|
1278
|
+
return false;
|
|
1279
|
+
const row = normalizeLastMarketFill(persisted);
|
|
1280
|
+
if (!row)
|
|
1281
|
+
return false;
|
|
1282
|
+
// Shared dead-row contract with restoreLastFillPivot: erase a rejected
|
|
1283
|
+
// row so it cannot re-arm the same rejection on every restart.
|
|
1284
|
+
const dropPersistedRow = () => {
|
|
1285
|
+
try {
|
|
1286
|
+
const acct = manager.accountOrders;
|
|
1287
|
+
if (acct && typeof acct.clearPersistedLastMarketFill === 'function') {
|
|
1288
|
+
void acct.clearPersistedLastMarketFill();
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
catch { /* best-effort */ }
|
|
1292
|
+
};
|
|
1293
|
+
const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
|
|
1294
|
+
const ttl = Number(GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS);
|
|
1295
|
+
if (Number.isFinite(ttl) && ttl > 0 && now - row.fillsAt > ttl) {
|
|
1296
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Persisted last-market-fill expired (age ${Math.round((now - row.fillsAt) / 1000)}s > TTL ${Math.round(ttl / 1000)}s) — reference dropped`, 'info');
|
|
1297
|
+
dropPersistedRow();
|
|
1298
|
+
return false;
|
|
1299
|
+
}
|
|
1300
|
+
manager._lastMarketFillPrice = row.price;
|
|
1301
|
+
manager._lastMarketFillType = row.type;
|
|
1302
|
+
manager._lastMarketFillAt = row.fillsAt;
|
|
1303
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Restored last-market-fill ${row.price}(${row.type}) age=${Math.round((now - row.fillsAt) / 1000)}s — spread correction will not trade through it`, 'info');
|
|
1304
|
+
return true;
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Shared field gate for a persisted fill-derived row: finite price > 0,
|
|
1308
|
+
* BUY/SELL side, finite positive timestamp. One shape contract for the
|
|
1309
|
+
* LAST-FILL-GUARD pivot row and the bot-scoped last-market-fill row.
|
|
989
1310
|
*
|
|
990
1311
|
* @param {unknown} row - Raw candidate row
|
|
991
|
-
* @returns {
|
|
1312
|
+
* @returns {{price:number,type:string,fillsAt:number}|null} Core fields or null
|
|
992
1313
|
*/
|
|
993
|
-
|
|
1314
|
+
function normalizeFillRow(row) {
|
|
994
1315
|
if (!row || typeof row !== 'object')
|
|
995
1316
|
return null;
|
|
996
1317
|
const r = row;
|
|
997
1318
|
const price = Number(r.price);
|
|
998
1319
|
const type = r.type;
|
|
999
1320
|
const fillsAt = Number(r.fillsAt);
|
|
1000
|
-
const genesisHash = r.genesisHash;
|
|
1001
1321
|
if (!Number.isFinite(price) || price <= 0)
|
|
1002
1322
|
return null;
|
|
1003
1323
|
if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
|
|
1004
1324
|
return null;
|
|
1005
1325
|
if (!Number.isFinite(fillsAt) || fillsAt <= 0)
|
|
1006
1326
|
return null;
|
|
1327
|
+
return { price, type, fillsAt };
|
|
1328
|
+
}
|
|
1329
|
+
/**
|
|
1330
|
+
* Normalize a persisted LAST-FILL-GUARD pivot row (shared by the
|
|
1331
|
+
* AccountOrders sanitizer/loader and the payload builder's row contract).
|
|
1332
|
+
*
|
|
1333
|
+
* The shared normalizeFillRow gate plus a non-empty string genesisHash (the
|
|
1334
|
+
* pivot is bound to the grid generation; the market row deliberately is not).
|
|
1335
|
+
*
|
|
1336
|
+
* @param {unknown} row - Raw candidate row
|
|
1337
|
+
* @returns {Object|null} Normalized row or null
|
|
1338
|
+
*/
|
|
1339
|
+
export function normalizeLastFillPivot(row) {
|
|
1340
|
+
const core = normalizeFillRow(row);
|
|
1341
|
+
if (!core)
|
|
1342
|
+
return null;
|
|
1343
|
+
const genesisHash = row.genesisHash;
|
|
1007
1344
|
if (typeof genesisHash !== 'string' || genesisHash.length === 0)
|
|
1008
1345
|
return null;
|
|
1009
|
-
return {
|
|
1346
|
+
return { ...core, genesisHash };
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Normalize a persisted bot-scoped last-market-fill row.
|
|
1350
|
+
*
|
|
1351
|
+
* Same normalizeFillRow contract as normalizeLastFillPivot but deliberately
|
|
1352
|
+
* WITHOUT the genesisHash binding: this row is market truth about the account
|
|
1353
|
+
* (the last price it traded at), not grid geometry, so it must survive a grid
|
|
1354
|
+
* regeneration/rejection. It is used only as a market reference by spread
|
|
1355
|
+
* correction, never as the COW LAST-FILL-GUARD pivot.
|
|
1356
|
+
*
|
|
1357
|
+
* @param {unknown} row - Raw candidate row
|
|
1358
|
+
* @returns {{price:number,type:string,fillsAt:number}|null} Normalized row or null
|
|
1359
|
+
*/
|
|
1360
|
+
export function normalizeLastMarketFill(row) {
|
|
1361
|
+
return normalizeFillRow(row);
|
|
1010
1362
|
}
|
|
1011
1363
|
/**
|
|
1012
1364
|
* Write the LAST-FILL-GUARD pivot scalar family in one place (free
|
|
@@ -1044,6 +1396,15 @@ export function setLastFillPivot(manager, type, price, provenance, atMs) {
|
|
|
1044
1396
|
manager._lastFilledBuyPrice = p;
|
|
1045
1397
|
else
|
|
1046
1398
|
manager._lastFilledSellPrice = p;
|
|
1399
|
+
// Bot-scoped market-fill reference: only a real fill is market truth. It
|
|
1400
|
+
// is deliberately NOT cleared by resetLastFillPivot/clearGrid — it must
|
|
1401
|
+
// survive a grid regeneration so spread correction still has a price it
|
|
1402
|
+
// cannot trade through (the genesis-bound pivot above does not).
|
|
1403
|
+
if (provenance === 'fill') {
|
|
1404
|
+
manager._lastMarketFillPrice = p;
|
|
1405
|
+
manager._lastMarketFillType = type;
|
|
1406
|
+
manager._lastMarketFillAt = now;
|
|
1407
|
+
}
|
|
1047
1408
|
return true;
|
|
1048
1409
|
}
|
|
1049
1410
|
/**
|
|
@@ -1226,7 +1587,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
|
|
|
1226
1587
|
// orders through the budget allocation below but never shift rails. The
|
|
1227
1588
|
// fund-ratio writer was removed — it moved the boundary without guaranteed
|
|
1228
1589
|
// same-batch refills, so a guard-vetoed refill stranded empty slots past
|
|
1229
|
-
// the new boundary (
|
|
1590
|
+
// the new boundary (<bot> 91->94) with no repair path. Remaining writers:
|
|
1230
1591
|
// fills (deriveTargetBoundary, same-cycle rotations) and spread promotion
|
|
1231
1592
|
// (shifts only onto slots placed in the same atomic batch).
|
|
1232
1593
|
let resizeCowResult = null;
|
|
@@ -1266,11 +1627,13 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
|
|
|
1266
1627
|
// GUARD keeps gap-band strays typed BUY/SELL (never SPREAD+ACTIVE), so
|
|
1267
1628
|
// without a geometric filter they are selected as "closest to market"
|
|
1268
1629
|
// and left inside the gap — collapsing the spread when a fill-driven
|
|
1269
|
-
// boundary shift moves into the rail (
|
|
1630
|
+
// boundary shift moves into the rail (<bot>: boundary 107->110 left
|
|
1270
1631
|
// the sell rail parked at 111-130 with the bottom three, 111-113,
|
|
1271
1632
|
// inside the new spread gap; real spread 0.5% instead of the 2.0%
|
|
1272
1633
|
// target).
|
|
1273
|
-
|
|
1634
|
+
// Absent-aware: Number(null)/Number('') === 0 would fabricate a
|
|
1635
|
+
// boundary-0 rail; only a real finite pending boundary wins.
|
|
1636
|
+
const workingBoundaryIdx = Number.isFinite(toKnownNumber(pendingBoundaryIdx))
|
|
1274
1637
|
? Number(pendingBoundaryIdx)
|
|
1275
1638
|
: manager.boundaryIdx;
|
|
1276
1639
|
const gapSlots = manager._genesis?.gapSlots ?? manager._gapSlots ?? MathUtils.calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
|
|
@@ -1303,24 +1666,24 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
|
|
|
1303
1666
|
.filter(inRailByType(orderType))
|
|
1304
1667
|
.sort((a, b) => sideName === 'buy' ? b.price - a.price : a.price - b.price);
|
|
1305
1668
|
// Calculate target count
|
|
1306
|
-
const
|
|
1307
|
-
const baseTargetCount = (
|
|
1308
|
-
? Math.max(1, Number(
|
|
1669
|
+
const coreOrdersCfg = manager.config.coreOrders;
|
|
1670
|
+
const baseTargetCount = (coreOrdersCfg && typeof coreOrdersCfg === 'object' && Number.isFinite(Number(coreOrdersCfg[sideName])))
|
|
1671
|
+
? Math.max(1, Number(coreOrdersCfg[sideName]))
|
|
1309
1672
|
: currentOnChainOrders.length;
|
|
1310
1673
|
const targetCount = baseTargetCount;
|
|
1311
|
-
// Determine desired slots (closest to market) + edge-pinned
|
|
1312
|
-
// Buys pin at the floor, sells at the ceiling.
|
|
1674
|
+
// Determine desired slots (closest to market) + edge-pinned orders.
|
|
1675
|
+
// Buys pin at the floor, sells at the ceiling. Edge orders rest live
|
|
1313
1676
|
// without consuming the window: the middle stays undesired and gets
|
|
1314
1677
|
// cancelled as surplus.
|
|
1315
1678
|
const windowSlots = allSideSlots.slice(0, targetCount);
|
|
1316
1679
|
let desiredSlots = windowSlots;
|
|
1317
|
-
const
|
|
1318
|
-
if (
|
|
1680
|
+
const edgeCount = OrderUtils.resolveEdgeCount(manager.config, sideName);
|
|
1681
|
+
if (edgeCount > 0) {
|
|
1319
1682
|
const asc = allSideSlots.slice().sort((a, b) => a.price - b.price);
|
|
1320
1683
|
const edge = sideName === 'sell' ? 'ceiling' : 'floor';
|
|
1321
1684
|
// Both edges anchor at the live grid's own edge (single source).
|
|
1322
|
-
const edgeAnchor = OrderUtils.
|
|
1323
|
-
const edgeSlots = OrderUtils.
|
|
1685
|
+
const edgeAnchor = OrderUtils.resolveLiveEdgeAnchorPrice(manager, sideName);
|
|
1686
|
+
const edgeSlots = OrderUtils.selectEdgeSlots(asc, edgeCount, new Set(windowSlots.map((s) => s.id)), edge, edgeAnchor);
|
|
1324
1687
|
desiredSlots = [...windowSlots, ...edgeSlots];
|
|
1325
1688
|
}
|
|
1326
1689
|
const desiredSlotIds = new Set(desiredSlots.map((s) => s.id));
|
|
@@ -1427,7 +1790,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
|
|
|
1427
1790
|
// executor already handles rotation UPDATEs (newGridId + newPrice remap).
|
|
1428
1791
|
const optimizedActions = optimizeRebalanceActions(actions, manager.orders, {
|
|
1429
1792
|
logger: (msg, level) => manager.logger?.log?.(msg, level),
|
|
1430
|
-
boundaryIdx: pendingBoundaryIdx,
|
|
1793
|
+
boundaryIdx: pendingBoundaryIdx ?? undefined,
|
|
1431
1794
|
gapSlots: manager._gapSlots,
|
|
1432
1795
|
assets: manager.assets
|
|
1433
1796
|
});
|
|
@@ -1438,14 +1801,14 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
|
|
|
1438
1801
|
// Refill-slot wire (boundary-hold): unpairable hole-CREATEs surviving
|
|
1439
1802
|
// the fold above justify the pending boundary shift. The executor
|
|
1440
1803
|
// holds the committed boundary when a listed refill is guard-skipped.
|
|
1441
|
-
//
|
|
1804
|
+
// Edge-ladder CREATEs are excluded by collectRefillSlotIds — static
|
|
1442
1805
|
// edge insurance, never a justification for a boundary shift.
|
|
1443
1806
|
const refillSlotIds = OrderUtils.collectRefillSlotIds(actions, {
|
|
1444
1807
|
config: manager.config,
|
|
1445
1808
|
slots: manager.orders,
|
|
1446
1809
|
edgeAnchors: {
|
|
1447
|
-
buy: OrderUtils.
|
|
1448
|
-
sell: OrderUtils.
|
|
1810
|
+
buy: OrderUtils.resolveLiveEdgeAnchorPrice(manager, 'buy'),
|
|
1811
|
+
sell: OrderUtils.resolveLiveEdgeAnchorPrice(manager, 'sell')
|
|
1449
1812
|
},
|
|
1450
1813
|
manager
|
|
1451
1814
|
});
|
|
@@ -220,7 +220,7 @@ declare function hasExecutableActions(rebalanceResult: unknown): boolean;
|
|
|
220
220
|
* with {chainOrderId, price, size, type} to check beyond the grid
|
|
221
221
|
* @returns {{isValid: boolean, violations: Array<Object>, violatingTargetIds: Set<string>}} Validation result
|
|
222
222
|
*/
|
|
223
|
-
declare function validateCreateTargetSlots(actions: CowAction[], orders: Map<string, ManagedOrder>, _assets?: AssetPair | null, chainOrderCandidates?: UnmatchedChainOrder[]): {
|
|
223
|
+
declare function validateCreateTargetSlots(actions: CowAction[], orders: Map<string, ManagedOrder>, _assets?: AssetPair | null, chainOrderCandidates?: UnmatchedChainOrder[], incrementPercent?: number | null): {
|
|
224
224
|
isValid: boolean;
|
|
225
225
|
violations: CreateTargetViolation[];
|
|
226
226
|
violatingTargetIds: Set<string>;
|