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
package/dist/unlock.js
CHANGED
|
@@ -25,10 +25,13 @@ const __dirname = _esmDirname(__filename);
|
|
|
25
25
|
* dexbot start --headless Non-interactive (requires env var or --password-file)
|
|
26
26
|
* dexbot start --headless --password-file <path>
|
|
27
27
|
* dexbot stat, status Runtime status
|
|
28
|
-
* dexbot stop
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* dexbot
|
|
28
|
+
* dexbot stop [<bot>] Stop the runtime. In monolithic mode a target folds
|
|
29
|
+
* into the whole runtime (one worker owns every bot);
|
|
30
|
+
* under --isolated it stops just that bot.
|
|
31
|
+
* dexbot reload [<bot>] Reload without re-unlocking the credential daemon
|
|
32
|
+
* (same target rules as stop)
|
|
33
|
+
* dexbot restart [<bot>] Restart (re-unlocks the credential daemon)
|
|
34
|
+
* dexbot delete Shut down and clean up (whole runtime only)
|
|
32
35
|
*
|
|
33
36
|
* Repo-root users can run `./unlock` instead.
|
|
34
37
|
* `dexbot unlock` is kept as a legacy alias for `dexbot start`.
|
|
@@ -71,7 +74,8 @@ const storage = getStorage();
|
|
|
71
74
|
const { ensureDir } = storage;
|
|
72
75
|
const { createBotSupervisor, SOCKET_PATH, forwardSignal, isPidAlive, waitForPidExit, readMarketAdapterLockPid, stopMarketAdapterFromLock, usesAmaGridPrice, waitForChildSpawn, pidMatchesScriptCandidates, candidateRuntimeScriptPaths, } = require('./modules/launcher/bot_supervisor');
|
|
73
76
|
const { statusTitle, statusLabel, statusBool, statusActiveBotName, statusSuccess, statusError, colorStatus, STATUS_COLORS, readProcStat, readProcMemMB, readProcCpuTime, readProcCpuPercent, readProcUptime, formatMemoryWithUptime, printControlStatus, } = require('./modules/launcher/status_reporting');
|
|
74
|
-
const { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, isProcessInDstate, stopCredentialDaemonPid, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, cleanupCredentialRuntimeFiles, readCredentialDaemonStatus, ensureLogDir: ensureMonolithicLogDir, buildDexbotStartArgs, createUpdateScheduler, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, printControlActionSummary, formatBotCount, } = require('./modules/launcher/monolithic_runtime');
|
|
77
|
+
const { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, isProcessInDstate, stopCredentialDaemonPid, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, cleanupCredentialRuntimeFiles, readCredentialDaemonStatus, ensureLogDir: ensureMonolithicLogDir, buildDexbotStartArgs, createUpdateScheduler, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, resolveControlRouting, botNotFoundMessage, printControlActionSummary, formatBotCount, } = require('./modules/launcher/monolithic_runtime');
|
|
78
|
+
const { isConfiguredBotName } = require('./modules/launcher/runtime_mode');
|
|
75
79
|
const CODE_ROOT = __dirname;
|
|
76
80
|
const BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
|
|
77
81
|
const LOGS_DIR = PATHS.LOGS_DIR;
|
|
@@ -324,12 +328,12 @@ async function launchDetachedSupervisor({ botName = null, credentialDaemonPid =
|
|
|
324
328
|
catch (_) { }
|
|
325
329
|
}
|
|
326
330
|
}
|
|
327
|
-
async function runIsolated({ botName, botEntry = null, stayResident = false, startupGraceMs = DEFAULT_STARTUP_GRACE_MS } = {}) {
|
|
331
|
+
async function runIsolated({ botName, botEntry = null, stayResident = false, startupGraceMs = DEFAULT_STARTUP_GRACE_MS, isolatedPollIntervalMs = 1000 } = {}) {
|
|
328
332
|
let supervisor;
|
|
329
333
|
if (botName) {
|
|
330
334
|
const bot = botEntry || resolveBotEntryForName(botName);
|
|
331
335
|
if (!bot) {
|
|
332
|
-
throw new Error(
|
|
336
|
+
throw new Error(botNotFoundMessage(botName));
|
|
333
337
|
}
|
|
334
338
|
supervisor = createBotSupervisor({ bots: [bot] });
|
|
335
339
|
}
|
|
@@ -383,7 +387,7 @@ async function runIsolated({ botName, botEntry = null, stayResident = false, sta
|
|
|
383
387
|
cleanupSignalHandlers();
|
|
384
388
|
reject(err);
|
|
385
389
|
}
|
|
386
|
-
},
|
|
390
|
+
}, isolatedPollIntervalMs);
|
|
387
391
|
});
|
|
388
392
|
}
|
|
389
393
|
// ── Main entry point ───────────────────────────────────────────────
|
|
@@ -440,7 +444,7 @@ async function runStartOnboardingIfNeeded({ allowInteractive = true, nonInteract
|
|
|
440
444
|
}
|
|
441
445
|
return true;
|
|
442
446
|
}
|
|
443
|
-
async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRACE_MS, exitAfterOnboarding = false, onboard = false } = {}) {
|
|
447
|
+
async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRACE_MS, isolatedPollIntervalMs = 1000, exitAfterOnboarding = false, onboard = false } = {}) {
|
|
444
448
|
if (typeof chainKeys.checkKeysFileSecurity === 'function')
|
|
445
449
|
chainKeys.checkKeysFileSecurity();
|
|
446
450
|
if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
|
|
@@ -502,7 +506,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
|
|
|
502
506
|
const shouldStartMonolithicBackground = !clawOnly && !isolated && !isDetachedSupervisorChild && !isMonolithicBgChild && !forceForeground;
|
|
503
507
|
let daemonReleased = false;
|
|
504
508
|
if (botName && !selectedBot) {
|
|
505
|
-
throw new Error(
|
|
509
|
+
throw new Error(botNotFoundMessage(botName));
|
|
506
510
|
}
|
|
507
511
|
if (shouldStartMonolithicBackground) {
|
|
508
512
|
const { pid } = readLiveMonolithicPid();
|
|
@@ -634,6 +638,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
|
|
|
634
638
|
botEntry: selectedBot,
|
|
635
639
|
stayResident: isDetachedSupervisorChild,
|
|
636
640
|
startupGraceMs,
|
|
641
|
+
isolatedPollIntervalMs,
|
|
637
642
|
});
|
|
638
643
|
return;
|
|
639
644
|
}
|
|
@@ -913,10 +918,37 @@ async function drainMonolithicWorkers(deadlineMs = 15000) {
|
|
|
913
918
|
return false;
|
|
914
919
|
}
|
|
915
920
|
async function handleControl({ cmd, target }) {
|
|
916
|
-
|
|
921
|
+
// Resolve the whole-runtime vs per-bot contract in one place. A live
|
|
922
|
+
// monolithic runtime owns every active bot in a single worker, so a bot
|
|
923
|
+
// target cannot be honored and degrades to the whole-runtime command with
|
|
924
|
+
// a printed notice (see resolveControlRouting). `all` is an alias for the
|
|
925
|
+
// whole runtime; `delete` rejects a bot target and `status` validates then
|
|
926
|
+
// ignores one.
|
|
927
|
+
const monolithic = readLiveMonolithicPid();
|
|
928
|
+
const routing = resolveControlRouting({ cmd, target, monolithicLive: monolithic.pid > 0 });
|
|
929
|
+
const effectiveCmd = routing.cmd;
|
|
930
|
+
const effectiveTarget = routing.target;
|
|
917
931
|
const actionLabel = getControlActionLabel(cmd);
|
|
918
|
-
if (
|
|
919
|
-
|
|
932
|
+
if (routing.reject) {
|
|
933
|
+
console.error(statusError(routing.reject));
|
|
934
|
+
process.exitCode = 1;
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
// Validate a target only when it is about to be folded into a whole-runtime
|
|
938
|
+
// action (monolithic, or an ignored `status`): a typo must not reload/stop
|
|
939
|
+
// every bot by mistake. A pass-through to the isolated supervisor is
|
|
940
|
+
// validated there against the bots it actually runs, so a bot renamed or
|
|
941
|
+
// removed from bots.json while running can still be controlled by name.
|
|
942
|
+
const requestedTarget = routing.requestedTarget;
|
|
943
|
+
if (routing.folded && requestedTarget && !isConfiguredBotName(requestedTarget)) {
|
|
944
|
+
console.error(statusError(botNotFoundMessage(requestedTarget)));
|
|
945
|
+
process.exitCode = 1;
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (routing.notice)
|
|
949
|
+
console.warn(routing.notice);
|
|
950
|
+
if ((effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'status' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all') && !effectiveTarget) {
|
|
951
|
+
const { pid, stale } = monolithic;
|
|
920
952
|
if (pid > 0) {
|
|
921
953
|
const summaryBotNames = getControlBotNames(undefined, true);
|
|
922
954
|
const summaryServiceNames = getControlServiceNames(effectiveCmd, summaryBotNames);
|
|
@@ -1092,11 +1124,11 @@ async function handleControl({ cmd, target }) {
|
|
|
1092
1124
|
// wrapper was killed without leaving a pid file, or cleanupStateFiles
|
|
1093
1125
|
// already ran). Drain before the isolated fall-through so that path cannot
|
|
1094
1126
|
// race a start into a duplicate worker.
|
|
1095
|
-
if (!
|
|
1127
|
+
if (!effectiveTarget && effectiveCmd !== 'status'
|
|
1096
1128
|
&& (effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all')) {
|
|
1097
1129
|
await drainMonolithicWorkers();
|
|
1098
1130
|
}
|
|
1099
|
-
if (effectiveCmd === 'delete' && !
|
|
1131
|
+
if (effectiveCmd === 'delete' && !effectiveTarget && storage.exists(MONOLITHIC_CRED_PID_FILE)) {
|
|
1100
1132
|
await sendIsolatedDeleteIfAvailable();
|
|
1101
1133
|
const credResult = await stopCredentialDaemon();
|
|
1102
1134
|
if (credResult.signaled) {
|
|
@@ -1110,10 +1142,10 @@ async function handleControl({ cmd, target }) {
|
|
|
1110
1142
|
}
|
|
1111
1143
|
// Fall through to isolated supervisor socket
|
|
1112
1144
|
const controlCmd = { cmd: effectiveCmd };
|
|
1113
|
-
if (
|
|
1114
|
-
controlCmd.bot =
|
|
1145
|
+
if (effectiveTarget)
|
|
1146
|
+
controlCmd.bot = effectiveTarget;
|
|
1115
1147
|
// Restart credential daemon for restart-all (no target) in isolated mode
|
|
1116
|
-
if (!
|
|
1148
|
+
if (!effectiveTarget && effectiveCmd === 'restart-all' && process.stdin.isTTY) {
|
|
1117
1149
|
const ownerPid = findCredentialSocketOwnerPid();
|
|
1118
1150
|
if (ownerPid > 0 && isLikelyCredentialDaemonProcess(ownerPid)) {
|
|
1119
1151
|
await stopCredentialDaemonPid(ownerPid);
|
|
@@ -1132,8 +1164,8 @@ async function handleControl({ cmd, target }) {
|
|
|
1132
1164
|
printControlStatus(resp.status);
|
|
1133
1165
|
}
|
|
1134
1166
|
else {
|
|
1135
|
-
if (
|
|
1136
|
-
const summaryBotNames = getControlBotNames(
|
|
1167
|
+
if (effectiveTarget || effectiveCmd === 'stop-all' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all' || effectiveCmd === 'delete') {
|
|
1168
|
+
const summaryBotNames = getControlBotNames(effectiveTarget, !effectiveTarget && (effectiveCmd === 'stop-all' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all' || effectiveCmd === 'delete'));
|
|
1137
1169
|
const summaryServiceNames = getControlServiceNames(effectiveCmd, summaryBotNames);
|
|
1138
1170
|
printControlActionSummary(actionLabel, summaryBotNames, summaryServiceNames);
|
|
1139
1171
|
}
|
|
@@ -1141,7 +1173,7 @@ async function handleControl({ cmd, target }) {
|
|
|
1141
1173
|
}
|
|
1142
1174
|
}
|
|
1143
1175
|
catch (err) {
|
|
1144
|
-
if (effectiveCmd === 'delete' && !
|
|
1176
|
+
if (effectiveCmd === 'delete' && !effectiveTarget && isSupervisorTransientError(err)) {
|
|
1145
1177
|
console.log('No runtime processes found.');
|
|
1146
1178
|
return;
|
|
1147
1179
|
}
|
|
@@ -304,6 +304,13 @@ You can re-run `dexbot bot` and save while the bot runs:
|
|
|
304
304
|
- **Market/account changes** — run `dexbot reload` (reloads the runtime
|
|
305
305
|
without logging you out; a full `restart` also works).
|
|
306
306
|
|
|
307
|
+
> `dexbot reload` / `restart` / `stop` are **whole-runtime** in the default
|
|
308
|
+
> monolithic mode: every active bot shares one worker process, so passing a bot
|
|
309
|
+
> name (e.g. `dexbot reload <bot>`) is validated and then applied to the whole
|
|
310
|
+
> runtime with a notice. To act on a single bot, start with `dexbot start
|
|
311
|
+
> --isolated` first. `delete` is whole-runtime and rejects a bot name; `status`
|
|
312
|
+
> is whole-runtime and validates, then ignores, one.
|
|
313
|
+
|
|
307
314
|
The editor prints exactly which group your save falls into every time it
|
|
308
315
|
saves, so you always know whether anything else is needed.
|
|
309
316
|
|
package/docs/COW_INVARIANTS.md
CHANGED
|
@@ -81,6 +81,12 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
81
81
|
- Validation chain (`restoreLastFillPivot`): TTL expiry (`GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS`, 24h; the pivot is a "latest fill" fact, not a permanent ratchet; expired pivots hand over to the startup book seed) and genesis binding (mismatched hash = dead generation) erase the row through one shared drop path (`clearPersistedLastFillPivot` under the bot's persistence lock, best-effort). Off-grid refusal (`resolveOnGridPivot` — the runtime's own ladder validator, imported lazily from the restore site so ONE implementation serves both the per-probe live guard and the restore; the restorer can never accept a value the runtime would refuse per probe) is a no-op that falls back to the book seed and leaves the row for the next snapshot flush to clear (the cold in-memory pivot makes the payload builder return null). The snapped ladder level is restored, never the raw float, and the ORIGINAL `fillsAt` is preserved through `setLastFillPivot`'s `atMs` param so the TTL keeps meaning "age of the last fill", not "time since this restart".
|
|
82
82
|
- Generation invalidation mirrors the pending-crawl ledger: `initializeGrid` and `rejectCorruptedGridSnapshot` clear the in-memory pivot via `resetLastFillPivot` (exposed as `OrderManager._resetLastFillPivot`), which clears the FULL scalar family — per-side mirrors included — so `seedLastFilledPricesFromBook`'s cold gate cannot be silently suppressed by stale per-side values after a grid rebuild, and `AccountOrders.clearGrid` wipes the persisted row with the snapshot. The guard re-arms on the first real fill of the new generation.
|
|
83
83
|
|
|
84
|
+
- `INV-COW-010` Grid-layer spread-correction cycle is atomic and bounded
|
|
85
|
+
- `checkSpreadCondition` holds the refcounted broadcast region (`startBroadcasting` / `stopBroadcasting`, released in `finally`) across its whole attempt loop, so a fill-driven rebalance defers rather than committing a master-version bump between the initial plan and its broadcast. This narrows the race; the COW commit guard remains the backstop.
|
|
86
|
+
- Before broadcasting, `resolveOccupiedCorrection` re-derives a plan whose CREATE destination became a live order since planning (`getOccupiedCorrectionSlots`), or withholds it — a known-taken slot is never shipped. The COW build layer stays authoritative against a detector false positive.
|
|
87
|
+
- A transient refusal re-plans ONCE from fresh master (`replanSpreadCorrectionFromFreshMaster`, bounded by `TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS`); a non-transient refusal (`commit-refused` / `update-target-missing` / `unmatched-chain-orders` / `shutdown`) is not retried and counts toward the out-of-spread stale clock.
|
|
88
|
+
- This is the grid layer's counterpart to `INV-COW-003` (COW-layer pre-broadcast re-plan) and to `INV-COW-007`'s broadcast-flag deferral contract.
|
|
89
|
+
|
|
84
90
|
- `INV-PROJ-001` New projected orders remain virtual
|
|
85
91
|
- Orders projected into empty slots must be `VIRTUAL` with no `orderId` until chain confirmation.
|
|
86
92
|
|
|
@@ -251,7 +257,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
251
257
|
|
|
252
258
|
- `INV-BATCH-001` Illegal state batch abort
|
|
253
259
|
- `executeBatch` throws `ILLEGAL_SPREAD_STATE` on an illegal grid layout (emitted at `modules/order/utils/validate.ts`, propagated via `modules/order/manager.ts` `_throwOnIllegalState`).
|
|
254
|
-
- The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:
|
|
260
|
+
- The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:533`) is a test-only dead branch — production never emits that code; only a test stub uses it.
|
|
255
261
|
- In production, recovery + cooldown are armed on the next maintenance tick via `_abortFlowIfIllegalState` (the `INV-MAINT-002` path), returning `abortedForIllegalState: true` to the caller. The caller does not need to return immediately; the maintenance tick handles recovery.
|
|
256
262
|
- Hard abort triggers one immediate recovery sync (`_triggerStateRecoverySync`) plus arms one maintenance cooldown cycle (`_maintenanceCooldownCycles = Math.max(current, 1)`).
|
|
257
263
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# DEXBot vs DEXBot2 — Detailed Comparison Report
|
|
2
2
|
|
|
3
3
|
> **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
|
|
4
|
-
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.
|
|
4
|
+
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.16).
|
|
5
5
|
> **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
|
|
6
6
|
|
|
7
7
|
---
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
| Attribute | DEXBot (original) | DEXBot2 |
|
|
38
38
|
|---|---|---|
|
|
39
|
-
| **Release Track** | 1.0.0 | v1.6.
|
|
39
|
+
| **Release Track** | 1.0.0 | v1.6.16 |
|
|
40
40
|
| **Language** | Python 3.6+ | TypeScript 5.x |
|
|
41
41
|
| **Status** | Released 1.0.0, unmaintained | Active development |
|
|
42
42
|
| **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
|
|
@@ -776,13 +776,13 @@ Where:
|
|
|
776
776
|
|
|
777
777
|
| Metric | DEXBot | DEXBot2 |
|
|
778
778
|
|---|---|---|
|
|
779
|
-
| **Release Track** | 1.0.0 | v1.6.
|
|
779
|
+
| **Release Track** | 1.0.0 | v1.6.16 |
|
|
780
780
|
| **Active Since** | ~2018 | December 2025 |
|
|
781
|
-
| **Last Commit** | May 23, 2020 | 2026-10-
|
|
782
|
-
| **Total Commits** | 2281 | 2,
|
|
781
|
+
| **Last Commit** | May 23, 2020 | 2026-10-18 |
|
|
782
|
+
| **Total Commits** | 2281 | 2,426 (current HEAD, v1.6.16 line) |
|
|
783
783
|
| **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
|
|
784
784
|
| **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
|
|
785
|
-
| **Test Files** | 16 Python test files |
|
|
785
|
+
| **Test Files** | 16 Python test files | 327 `test_*.ts` files (310 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |
|
|
786
786
|
| **Documentation** | Sphinx docs + README | 60+ Markdown docs plus Claw skills/references |
|
|
787
787
|
| **Strategies** | 3 + plugins | 1 |
|
|
788
788
|
| **Max Concurrent Bots** | Many (one process) | Many (one monolithic process by default; per-bot via `--isolated`/PM2) |
|
package/docs/EVOLUTION.md
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## Executive Summary
|
|
4
4
|
|
|
5
|
-
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.
|
|
5
|
+
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.16 release.
|
|
6
6
|
|
|
7
7
|
### Key Milestones
|
|
8
8
|
- **Project Inception**: December 2, 2025
|
|
9
|
-
- **Growth Phase**: 2,
|
|
9
|
+
- **Growth Phase**: 2,426 commits over ~9 active months
|
|
10
10
|
- **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
|
|
11
|
-
- **Stability**: Progression from manual testing to a suite of
|
|
12
|
-
- **Releases**:
|
|
11
|
+
- **Stability**: Progression from manual testing to a suite of 310 automated test files
|
|
12
|
+
- **Releases**: 148 version entries in the changelog (v0.1.0 to v1.6.16)
|
|
13
13
|
|
|
14
14
|
> **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
|
|
15
15
|
> bug families, and lessons — lives in
|
|
@@ -149,7 +149,7 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
|
|
|
149
149
|
|
|
150
150
|
## Version History
|
|
151
151
|
|
|
152
|
-
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-
|
|
152
|
+
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-18). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,319 (`v0.1.0..HEAD`) and 2,426 (`HEAD`); the `v1.4.x` era rows overlap slightly because `v1.4.13` is not an ancestor of `v1.4.25` in the current history. Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
|
|
153
153
|
|
|
154
154
|
| Era | Commits | Theme |
|
|
155
155
|
|-----|--------:|-------|
|
|
@@ -171,12 +171,14 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
|
|
|
171
171
|
| v1.6.10 → v1.6.11 | 6 | AMA-slope 3-bar persistence gate + 16h Huber lookback, EMA-smoothing removal, PnL HTML report + month-shard fill cache, five order-engine/lifecycle safety fixes |
|
|
172
172
|
| v1.6.11 → v1.6.12 | 27 | Explicit-`any` elimination + ratchet, shared ECC core & Firefox-safe pure-JS scrypt, worker-drain and fresh-placement cancel-grace safety fixes, funded spread correction, partial credit renewal, update install-layout classifier, AMA persistence-override fixes, test-suite speedup, dynamic-weight knob retune |
|
|
173
173
|
| v1.6.12 → v1.6.13 | 21 | Spread-stall cause reporting + chain sync on every stall, resync-cascade guards (uncertain broadcast / suspended persistence), month-shard candle cache, dedup & dead-code purge, npm 12 install & PM2 fixes |
|
|
174
|
-
| v1.6.13 → v1.6.14 |
|
|
174
|
+
| v1.6.13 → v1.6.14 | 18 | Last-fill guard + live market floor for spread correction, committed-size drift resize, COW pre-broadcast guards & P2 counters, fail-closed unknown geometry, order-key rename, worker-thread test runner |
|
|
175
|
+
| v1.6.14 → v1.6.15 | 20 | Spread-correction resilience (atomic plan/retry, bounded re-plan, transient-refusal grace), price-vs-amount level identity for low-precision assets, credit-renewal free-collateral top-up, TradingView 1h/chart fixes & live data-age badge, per-asset `dexbot rich`, ~4x parallel test runner |
|
|
176
|
+
| v1.6.15 → v1.6.16 | 14 | Monolithic per-bot control routing, orientation-shared candle cache, market-profile orientation tolerance, chart log-axis hang fix + viewport-clipped draw hooks, Firefox Playwright chart suite, adapter-whitelist rename/copy sync, `dexbot rich` symbol canonicalization, doc reconciliation |
|
|
175
177
|
|
|
176
178
|
---
|
|
177
179
|
|
|
178
180
|
**Report Originally Generated**: February 19, 2026
|
|
179
|
-
**Last Updated**: October
|
|
180
|
-
**Total Commits**: 2,
|
|
181
|
-
**Date Range**: December 2, 2025 – October
|
|
181
|
+
**Last Updated**: October 18, 2026
|
|
182
|
+
**Total Commits**: 2,426
|
|
183
|
+
**Date Range**: December 2, 2025 – October 18, 2026
|
|
182
184
|
**Repository**: DEXBot2 (BitShares DEX Trading Bot)
|
|
@@ -52,7 +52,7 @@ funds.allocated → _getSizingContext() (budget for spread correction)
|
|
|
52
52
|
**Key points:**
|
|
53
53
|
- `botFunds` percentage applies to **total** capital (free + locked in orders), not just free. A bot at `"50%"` gets half of everything, not half of what's currently idle.
|
|
54
54
|
- `funds.allocated` is the ceiling for each side. Existing orders already consume part of it; the remaining free portion is available for new placements.
|
|
55
|
-
- The downstream `applyBotFundsAllocation()` (`manager.ts:
|
|
55
|
+
- The downstream `applyBotFundsAllocation()` (`manager.ts:1287`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
|
|
56
56
|
|
|
57
57
|
---
|
|
58
58
|
|
|
@@ -123,7 +123,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
|
|
|
123
123
|
**Per-Batch Execution**:
|
|
124
124
|
|
|
125
125
|
1. **Peek & Pop**: Check `_incomingFillQueue`, pop up to N fills (batch size)
|
|
126
|
-
2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:
|
|
126
|
+
2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:300`)
|
|
127
127
|
- Proceeds credited directly to `chainFree` (via `adjustTotalBalance`)
|
|
128
128
|
- Same-order fill batching (sync_engine Phase 6 cumulative transition) aggregates multiple fill transitions on one order before a single rebalance
|
|
129
129
|
- All proceeds immediately available to next rebalance cycle (not split across cycles)
|
|
@@ -803,4 +803,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
|
|
|
803
803
|
**TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
|
|
804
804
|
|
|
805
805
|
---
|
|
806
|
-
*Technical Reference for DEXBot2 v1.6.
|
|
806
|
+
*Technical Reference for DEXBot2 v1.6.16 release*
|
|
@@ -158,13 +158,19 @@ node dist/market_adapter/market_adapter.js --deltaPercent 2
|
|
|
158
158
|
```json
|
|
159
159
|
{
|
|
160
160
|
"ama": {
|
|
161
|
-
"erPeriod":
|
|
162
|
-
"fastPeriod": 2,
|
|
163
|
-
"slowPeriod":
|
|
161
|
+
"erPeriod": 781, // Efficiency Ratio lookback period (candles)
|
|
162
|
+
"fastPeriod": 5.2, // Fast smoothing period for trending markets
|
|
163
|
+
"slowPeriod": 83.6 // Slow smoothing period for choppy markets
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
```
|
|
167
167
|
|
|
168
|
+
> Optional. A bot-level `ama` block overrides the preset (or matched pair profile)
|
|
169
|
+
> field by field, and supplying any period marks the bot's AMA as `custom` in the
|
|
170
|
+
> adapter state. The values above are the fitted `AMA3` built-in defaults
|
|
171
|
+
> (`MARKET_ADAPTER.AMAS`): `erPeriod: 781` and `fastPeriod: 5.2` are shared, while
|
|
172
|
+
> `slowPeriod` runs `62.1` (AMA1) to `96.9` (AMA4).
|
|
173
|
+
|
|
168
174
|
> **`gridPrice` is the only switch.** A bot is AMA-driven when `gridPrice` says
|
|
169
175
|
> so — `usesAmaGridPrice()`, the source of truth shared by the bot, maintenance
|
|
170
176
|
> and launcher runtimes. There is deliberately no `ama.enabled`: a second switch
|
|
@@ -199,9 +205,15 @@ The pool is fetched directly by ID, bypassing pool discovery. Useful when the tr
|
|
|
199
205
|
- Higher = more lag, filters noise
|
|
200
206
|
- Built-in presets range from `AMA1` (fastest) to `AMA4` (slowest) — see `MARKET_ADAPTER.AMAS` in `modules/constants.ts` for the exact `slowPeriod` values
|
|
201
207
|
|
|
202
|
-
AMA parameters
|
|
203
|
-
|
|
204
|
-
|
|
208
|
+
AMA parameters resolve in this order: a matched pair profile in
|
|
209
|
+
`profiles/market_profiles.json` wins for that pair; otherwise the bot's own `ama`
|
|
210
|
+
block overrides the preset field by field; any period the bot does not supply is
|
|
211
|
+
taken from the preset named by `gridPrice` (`"ama"` → the pair's `defaultAma`,
|
|
212
|
+
which falls back to `AMA3`; `"ama1"`–`"ama4"` → that exact preset); and any
|
|
213
|
+
remaining missing field falls back to the built-in `MARKET_ADAPTER.AMAS` defaults
|
|
214
|
+
(`modules/constants.ts`, default key `AMA3`). A bot that hand-writes any of the
|
|
215
|
+
three periods is reported as `custom` in the adapter state rather than by a preset
|
|
216
|
+
name.
|
|
205
217
|
|
|
206
218
|
### How It Works
|
|
207
219
|
|
package/docs/LIFECYCLE.md
CHANGED
|
@@ -90,7 +90,7 @@ sequenceDiagram
|
|
|
90
90
|
participant CO as chain_orders (broadcast)
|
|
91
91
|
participant STORE as Storage
|
|
92
92
|
|
|
93
|
-
CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:
|
|
93
|
+
CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:463)
|
|
94
94
|
FR->>FR: drain queue -> _processFillsWithBatching
|
|
95
95
|
FR->>OM: processFilledOrders() (manager.ts)
|
|
96
96
|
OM->>AC: processFillAccounting() (single call, batch)
|
|
@@ -134,9 +134,9 @@ sequenceDiagram
|
|
|
134
134
|
participant STORE as Storage
|
|
135
135
|
|
|
136
136
|
MA->>CL: AMA center snapshot updated
|
|
137
|
-
CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:
|
|
137
|
+
CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1747)
|
|
138
138
|
CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1677)
|
|
139
|
-
RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:
|
|
139
|
+
RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2981)
|
|
140
140
|
RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:2462)
|
|
141
141
|
RT->>AC: recalculate funds from balances
|
|
142
142
|
RT->>GD: promote AMA center -> grid center
|
|
@@ -157,13 +157,13 @@ The AMA signal stack (AMA/Kalman/Hurst/PE) is *research-tuned* in `analysis/` an
|
|
|
157
157
|
the parameters.
|
|
158
158
|
|
|
159
159
|
> Note: `runMaintenance()` is a **different** subsystem — the credit/MPA debt
|
|
160
|
-
> runtime (`modules/credit_runtime.ts:
|
|
161
|
-
> `_runCreditRuntimeMaintenance` at `dexbot_class.ts:
|
|
160
|
+
> runtime (`modules/credit_runtime.ts:3623`, reached via
|
|
161
|
+
> `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1864`). The grid maintenance
|
|
162
162
|
> chain above is the one that matters for order/price upkeep.
|
|
163
163
|
|
|
164
|
-
References: `modules/dexbot_class.ts:
|
|
164
|
+
References: `modules/dexbot_class.ts:1747` (`_performPeriodicGridChecks`) →
|
|
165
165
|
`modules/dexbot_maintenance_runtime.ts:1677` (`performPeriodicGridChecks`) →
|
|
166
|
-
`:
|
|
166
|
+
`:2981` (`runGridMaintenance`) → `:2462` (`executeMaintenanceLogic`),
|
|
167
167
|
`docs/GRID_RECALCULATION.md`, `docs/GRID_RECONCILE.md`.
|
|
168
168
|
|
|
169
169
|
---
|
|
@@ -192,7 +192,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
|
|
|
192
192
|
| How a fill becomes orders | `modules/dexbot_fill_runtime.ts` → `modules/order/manager.ts` |
|
|
193
193
|
| Grid math / recalculation | `modules/order/grid.ts`, `docs/GRID_RECALCULATION.md` |
|
|
194
194
|
| Funds & accounting | `modules/order/accounting.ts`, `docs/FUND_MOVEMENT_AND_ACCOUNTING.md` |
|
|
195
|
-
| Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:
|
|
195
|
+
| Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1747` |
|
|
196
196
|
| Market signal source | `market_adapter/market_adapter.ts`, `analysis/README.md` |
|
|
197
197
|
| Startup & orchestration | `modules/dexbot_class.ts`, `docs/developer_guide.md` §"Startup Sequence" |
|
|
198
198
|
| Why COW exists | `docs/architecture.md` §"Copy-on-Write (COW) Grid Pattern", `docs/COW_INVARIANTS.md` |
|
package/docs/LOGGING.md
CHANGED
|
@@ -248,7 +248,7 @@ Prefix tags used in log messages to help operators identify event types. To find
|
|
|
248
248
|
| `[TARGETED-SYNC]` | `dexbot_maintenance_runtime.ts` | Targeted drift synchronization deferral |
|
|
249
249
|
| `[MULTI-BOT]` | `chain_orders.ts` | Multi-bot shared-account coordination |
|
|
250
250
|
| `[BTS-FEE]` | `order/accounting.ts` | BTS fee deferred accounting |
|
|
251
|
-
| `[SPREAD-CORRECTION]` | `order/grid.ts` |
|
|
251
|
+
| `[SPREAD-CORRECTION]` | `order/grid.ts` | Spread correction, plan-time CREATE dedupe, and bounded fresh-master re-plan |
|
|
252
252
|
| `[STRATEGY]` | `order/strategy.ts` | Fee event cache and strategy decisions |
|
|
253
253
|
| `[RECONCILE]` | `order/utils/validate.ts` | Grid reconciliation ([GRID_RECONCILE.md](GRID_RECONCILE.md)) |
|
|
254
254
|
| `[RMS]` | `order/grid.ts`, `dexbot_maintenance_runtime.ts` | RMS structural-divergence checks: per-side `metric vs threshold → TRIGGER-RESYNC/no trigger` at `debug` (plus a `checks disabled` variant when the threshold is 0), reset line with threshold + breaching sides at `info` |
|
|
@@ -295,6 +295,21 @@ Counter-only signals (none gate placement) surfaced through `getMetrics()`: `ref
|
|
|
295
295
|
| `[COW-GAP-BAND] shadow: N non-spread-correction placement(s) inside the plan's gap band (...)` | Mode C(a) shadow: an in-gap rail placement that is not spread correction / gap evacuation. Counted, never blocked; warned once per batch |
|
|
296
296
|
| `[BOUNDARY-DRIFT] committed boundary X -> planned Y (drift N slots) exceeds active window W; boundary is detached from the market anchor (observability only)` | A single plan moved the boundary more than the active window (absolute recovery anchor or geometry fault). Counted; rate-limited warn |
|
|
297
297
|
|
|
298
|
+
### Spread-correction resilience
|
|
299
|
+
|
|
300
|
+
Counter-only signals (none gate placement) surfaced through `getMetrics()`:
|
|
301
|
+
`spreadCorrectionRefusedCount` (all refusals), `spreadCorrectionRefusalCauses`
|
|
302
|
+
(per-`SPREAD_CORRECTION_REFUSAL` cause), and `spreadCorrectionRetryCount` (bounded
|
|
303
|
+
re-plan retries). Kept separate from the generic `refusedCommitCount`.
|
|
304
|
+
|
|
305
|
+
| Message | Meaning |
|
|
306
|
+
|---------|---------|
|
|
307
|
+
| `[SPREAD-CORRECTION] Plan-time dedupe: N planned slot(s) occupied since planning (...); re-planning from fresh master` | A planned CREATE destination was taken after planning; the plan is re-derived from fresh master |
|
|
308
|
+
| `[SPREAD-CORRECTION] Plan-time dedupe: ...; no re-plan candidate — refusing this cycle` | Collision detected but no fresh candidate exists; the colliding plan is withheld (never broadcast) |
|
|
309
|
+
| `[SPREAD-CORRECTION] Batch refused (cause); re-planning from fresh master (attempt 2/2)` | Transient refusal; the bounded fresh-master re-plan is in progress |
|
|
310
|
+
| `Spread correction batch was prepared but not executed. Keeping local state unchanged. (cause=...)` | Terminal refusal; `cause` is the classified `SPREAD_CORRECTION_REFUSAL` value |
|
|
311
|
+
| `Shutdown complete. Final metrics: ... spreadCorrectionRefusals=N [cause=count, ...], spreadCorrectionRetries=M` | Refusal breakdown on shutdown; the suffix appears only when at least one refusal occurred |
|
|
312
|
+
|
|
298
313
|
---
|
|
299
314
|
|
|
300
315
|
## Fill History Scan Profiling
|
package/docs/MPA_CREDIT_USAGE.md
CHANGED
|
@@ -73,7 +73,7 @@ Add `debtPolicy` to a bot entry in `profiles/bots.json`:
|
|
|
73
73
|
|
|
74
74
|
### Field Reference
|
|
75
75
|
|
|
76
|
-
<details><summary>All config fields (click to expand)</summary>
|
|
76
|
+
<details><summary><mark>All config fields (click to expand)</mark></summary>
|
|
77
77
|
|
|
78
78
|
**Required Fields:**
|
|
79
79
|
|
|
@@ -118,6 +118,7 @@ Add `debtPolicy` to a bot entry in `profiles/bots.json`:
|
|
|
118
118
|
| `allowedOfferIds` | `string[]` | No | Whitelist of credit offer object IDs (1.21.x) the bot may accept. |
|
|
119
119
|
| `disallowedDealIds` | `string[]` | No | Denylist of credit deal object IDs (1.22.x) the bot must not reborrow from. Repay is unaffected — the bot can still repay deals in this list. |
|
|
120
120
|
| `renewOnly` | `boolean` | No | If `true`, the bot only reborrows existing deals — standalone credit borrows are refused. Default `false`. |
|
|
121
|
+
| `useFreeCollateral` | `boolean` | No | Defaults to `true`: a renewal locks the borrower's free balance of the collateral asset in addition to the collateral the repay released, so the reborrow can keep the original principal when the offer's collateral price moved. Set to `false` to opt out and cap each reborrow to the released collateral only. |
|
|
121
122
|
| `minDurationSeconds` | `number` | No | Minimum acceptable offer duration in seconds. Offers with `duration_seconds` below this value are skipped. |
|
|
122
123
|
|
|
123
124
|
**Global Fields:**
|
|
@@ -277,11 +278,15 @@ The repay leg is funded from the borrower's *free* debt-asset balance before the
|
|
|
277
278
|
|
|
278
279
|
The reborrow snapshots the pre-repay deal IDs, so the stale-entry guard only drops a request when a deal *appeared after* the repay on the same offer — sibling deals no longer block a legitimate reborrow.
|
|
279
280
|
|
|
280
|
-
#### Collateral Shortfall Scaling
|
|
281
|
+
#### Collateral Top-Up and Shortfall Scaling
|
|
281
282
|
|
|
282
|
-
A reborrow
|
|
283
|
+
A reborrow starts from the collateral the repay just released. If the offer's collateral price moved, the full debt may need more collateral than the deal holds. By default (`useFreeCollateral: true`) the runtime adds the borrower's free balance of the same collateral asset to that budget, so the reborrow re-locks the original principal instead of shrinking. Set `useFreeCollateral: false` on the lending item to keep the legacy released-collateral-only ceiling and let the position deleverage on a price move.
|
|
284
|
+
|
|
285
|
+
The top-up stays within the position's `assignedCollateralBudget`, so it cannot take collateral allocated to sibling positions on a shared account. If the collateral asset is also a grid asset (for example BTS), the top-up locks funds the grid would otherwise have free — that is the intended trade-off of the feature.
|
|
283
286
|
|
|
284
287
|
- `buildCreditOfferAcceptOperation` takes an optional raw `availableCollateralAmount` budget and shrinks the borrow to the maximum that budget can back at the offer price (`capBorrowToCollateral`). It lives in the shared builder, so original, fallback, and deferred reborrows all get it.
|
|
288
|
+
- With `useFreeCollateral: false`, only `floor(repay * collateral / debt)` from the repaid deal is available, so a price move against the collateral scales the borrow down. The free-balance read is skipped when the released collateral already backs the borrow at the current offer price.
|
|
289
|
+
- A deferred reborrow re-reads the current free balance and position budget on each retry, so its ceiling tracks the live state rather than a queue-time snapshot. The collateral-switch flow is the exception: its budget is the new asset's total balance, not freed collateral, so a retry reuses the stored value instead of adding the free balance again.
|
|
285
290
|
- A clamped borrow below `min_deal_amount` is deferred and retried (up to `TIMING.CREDIT_REBORROW_MAX_ATTEMPTS`, default `6`) so a price recovery can revive it; after the limit it is dropped. The repay still proceeds, so the position deleverages.
|
|
286
291
|
- The collateral-switch flow passes the new asset's balance as the budget.
|
|
287
292
|
- Each accept records `requestedBorrowAmount` vs `borrowAmount` and `clampedByCollateral` in `lastBorrowRequest`.
|
|
@@ -300,7 +305,7 @@ You can switch a credit deal's collateral to a different asset on its next renew
|
|
|
300
305
|
|
|
301
306
|
On each maintenance cycle, the runtime compares each deal's on-chain `auto_repay` against the policy's `autoRepay` value. If they differ, a `credit_deal_update` operation is broadcast. After a successful update, the local deal state is updated to prevent redundant broadcasts on the next cycle.
|
|
302
307
|
|
|
303
|
-
<details><summary>BitShares auto-repay modes (click to expand)</summary>
|
|
308
|
+
<details><summary><mark>BitShares auto-repay modes (click to expand)</mark></summary>
|
|
304
309
|
|
|
305
310
|
BitShares core 7.0.2 defines three auto-repay modes:
|
|
306
311
|
|
|
@@ -359,7 +364,7 @@ Treat this file as runtime state, not primary configuration. The source of truth
|
|
|
359
364
|
|
|
360
365
|
## Related Files
|
|
361
366
|
|
|
362
|
-
<details><summary>Source files and tests (click to expand)</summary>
|
|
367
|
+
<details><summary><mark>Source files and tests (click to expand)</mark></summary>
|
|
363
368
|
|
|
364
369
|
- `modules/credit_runtime.ts`: debt workflow executor (Phase 0 oversized-deal splitter lives here)
|
|
365
370
|
- `modules/credit_pricing.ts`: canonical credit-pricing math (offer orientation, conversion rates, CR, fees) shared by runtime and analyzer
|