dexbot 1.6.12 → 1.6.13
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 +33 -1
- package/analysis/README.md +9 -11
- package/analysis/ama_fitting/README.md +5 -3
- package/claw/README.md +1 -0
- package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
- package/claw/modules/claw_bridge.ts +0 -3
- package/claw/modules/claw_skill_md.ts +1 -0
- package/claw/package.json +3 -3
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/claw/tsconfig.json +2 -2
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
- package/dist/analysis/analyze_args.d.ts +12 -0
- package/dist/analysis/analyze_args.js +20 -0
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
- package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
- package/dist/analysis/bot_fitting/shared_utils.js +124 -8
- package/dist/analysis/chart_ui.d.ts +30 -1
- package/dist/analysis/chart_ui.js +37 -1
- package/dist/analysis/fills_cache.d.ts +3 -23
- package/dist/analysis/fills_cache.js +3 -84
- package/dist/analysis/fills_source.d.ts +31 -1
- package/dist/analysis/fills_source.js +69 -1
- package/dist/analysis/grid_correction_check.d.ts +1 -23
- package/dist/analysis/grid_correction_check.js +15 -58
- package/dist/analysis/math_utils.d.ts +85 -1
- package/dist/analysis/math_utils.js +116 -1
- package/dist/analysis/price_sources.d.ts +22 -1
- package/dist/analysis/price_sources.js +23 -0
- package/dist/analysis/resolve_source.js +31 -10
- package/dist/analysis/trade_profitability.d.ts +6 -0
- package/dist/analysis/trade_profitability.js +23 -97
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
- package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
- package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
- package/dist/analysis/worker_pool.d.ts +38 -0
- package/dist/analysis/worker_pool.js +67 -0
- package/dist/dexbot.js +67 -48
- package/dist/market_adapter/ama_signal_runner.js +21 -54
- package/dist/market_adapter/candle_utils.d.ts +7 -1
- package/dist/market_adapter/candle_utils.js +11 -1
- package/dist/market_adapter/cli_args.d.ts +22 -0
- package/dist/market_adapter/cli_args.js +30 -0
- package/dist/market_adapter/core/config_normalizers.js +11 -6
- package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
- package/dist/market_adapter/core/kibana_candles.js +3 -2
- package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
- package/dist/market_adapter/core/market_adapter_service.js +93 -158
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
- package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
- package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
- package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
- package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
- package/dist/market_adapter/inputs/window_cache.js +52 -177
- package/dist/market_adapter/interval_utils.d.ts +11 -1
- package/dist/market_adapter/interval_utils.js +16 -1
- package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
- package/dist/market_adapter/lp_chart_runner.js +37 -19
- package/dist/market_adapter/market_adapter.js +27 -72
- package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
- package/dist/market_adapter/utils/data_discovery.js +220 -27
- package/dist/market_adapter/utils/month_shards.d.ts +84 -0
- package/dist/market_adapter/utils/month_shards.js +237 -0
- package/dist/modules/account_bots.d.ts +1 -0
- package/dist/modules/account_bots.js +102 -121
- package/dist/modules/account_orders.d.ts +13 -0
- package/dist/modules/account_orders.js +38 -44
- package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
- package/dist/modules/bitshares-native/chain_client.js +14 -13
- package/dist/modules/bitshares-native/resolvers.js +22 -25
- package/dist/modules/bitshares-native/serial/types.js +22 -50
- package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
- package/dist/modules/bot_defaults.d.ts +2 -1
- package/dist/modules/bot_settings.d.ts +1 -1
- package/dist/modules/broadcast_failure.d.ts +2 -1
- package/dist/modules/chain_orders.d.ts +1 -1
- package/dist/modules/chain_orders.js +51 -96
- package/dist/modules/cli_start_onboarding.d.ts +2 -1
- package/dist/modules/constants.d.ts +7 -1
- package/dist/modules/constants.js +20 -1
- package/dist/modules/cr_planner.d.ts +1 -1
- package/dist/modules/cr_planner.js +1 -5
- package/dist/modules/credit_pricing.d.ts +2 -1
- package/dist/modules/credit_pricing.js +36 -40
- package/dist/modules/credit_runtime.d.ts +7 -0
- package/dist/modules/credit_runtime.js +45 -73
- package/dist/modules/daemon_node_health.d.ts +4 -3
- package/dist/modules/dexbot_class.d.ts +28 -17
- package/dist/modules/dexbot_class.js +105 -58
- package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
- package/dist/modules/dexbot_cow_runtime.js +54 -28
- package/dist/modules/dexbot_credential_client.d.ts +0 -7
- package/dist/modules/dexbot_credential_client.js +1 -2
- package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
- package/dist/modules/dexbot_fill_runtime.js +5 -6
- package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
- package/dist/modules/dexbot_maintenance_runtime.js +84 -69
- package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
- package/dist/modules/dexbot_startup_runtime.js +13 -14
- package/dist/modules/general_settings.d.ts +1 -1
- package/dist/modules/graceful_shutdown.js +17 -11
- package/dist/modules/key_store.js +0 -1
- package/dist/modules/lazy_shim.d.ts +11 -0
- package/dist/modules/lazy_shim.js +16 -0
- package/dist/modules/node_connect_policy.d.ts +3 -2
- package/dist/modules/node_failure_ledger.d.ts +6 -5
- package/dist/modules/order/format.d.ts +12 -3
- package/dist/modules/order/format.js +15 -3
- package/dist/modules/order/genesis_policy.d.ts +3 -3
- package/dist/modules/order/genesis_policy.js +5 -2
- package/dist/modules/order/grid.d.ts +4 -2
- package/dist/modules/order/grid.js +91 -35
- package/dist/modules/order/index.d.ts +1 -0
- package/dist/modules/order/logger.d.ts +1 -8
- package/dist/modules/order/logger.js +0 -9
- package/dist/modules/order/manager.d.ts +9 -13
- package/dist/modules/order/manager.js +33 -50
- package/dist/modules/order/utils/order.js +39 -35
- package/dist/modules/order/utils/system.d.ts +9 -29
- package/dist/modules/order/utils/system.js +17 -2
- package/dist/modules/order/utils/validate.js +2 -2
- package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
- package/dist/modules/paths.js +32 -34
- package/dist/modules/runtime_settings.d.ts +2 -4
- package/dist/modules/settings_merge.d.ts +2 -2
- package/dist/modules/socket_json_client.d.ts +2 -1
- package/dist/modules/types.d.ts +42 -27
- package/dist/modules/utils/errors.js +1 -3
- package/dist/modules/version_notice.d.ts +11 -10
- package/dist/pm2.d.ts +0 -1
- package/dist/pm2.js +56 -35
- package/dist/scripts/analyze-git.js +2 -15
- package/dist/scripts/chart_command.js +2 -2
- package/dist/scripts/check_any.d.ts +4 -0
- package/dist/scripts/check_any.js +53 -21
- package/dist/scripts/diagnose-pool-history.js +1 -6
- package/dist/scripts/run-tests.js +0 -1
- package/dist/scripts/sync-version.js +0 -10
- package/docs/BITSHARES_ONBOARDING.md +8 -12
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +9 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/README.md +1 -1
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +19 -10
- package/market_adapter/README.md +6 -4
- package/package.json +6 -9
- package/scripts/README.md +43 -38
- package/tests/README.md +25 -10
- package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
- package/dist/scripts/diagnose-kibana-candles.js +0 -82
- package/scripts/git-viewer.sh +0 -489
- package/scripts/postinstall.js +0 -16
|
@@ -2,14 +2,15 @@
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import os from 'node:os';
|
|
5
|
-
import { pathToFileURL
|
|
6
|
-
import {
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
7
7
|
import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
|
|
8
8
|
import { toIntervalLabel } from '../../market_adapter/interval_utils.js';
|
|
9
9
|
import { generateHTML } from '../../market_adapter/lp_chart_core.js';
|
|
10
10
|
import { PATHS } from '../../modules/paths.js';
|
|
11
11
|
import { ensureDir } from '../../modules/order/utils/system.js';
|
|
12
|
-
import { range } from '../math_utils.js';
|
|
12
|
+
import { range, geometricRange, percentile } from '../math_utils.js';
|
|
13
|
+
import { runModuleWorker, splitIntoShards } from '../worker_pool.js';
|
|
13
14
|
import { getStorage } from '../../modules/storage/index.js';
|
|
14
15
|
import { normalizeAssetSymbol } from '../../modules/utils/asset_symbols.js';
|
|
15
16
|
const { readJSON, writeJSON } = getStorage();
|
|
@@ -53,27 +54,6 @@ const AMA_OBJECTIVES = [
|
|
|
53
54
|
function cloneObjectives() {
|
|
54
55
|
return AMA_OBJECTIVES.map((o) => ({ ...o }));
|
|
55
56
|
}
|
|
56
|
-
// ── Parameter ranges ──────────────────────────────────────────────────────────
|
|
57
|
-
function quantize(value, quantum) {
|
|
58
|
-
if (quantum == null || !Number.isFinite(quantum) || quantum <= 0)
|
|
59
|
-
return value;
|
|
60
|
-
return Math.round(value / quantum) * quantum;
|
|
61
|
-
}
|
|
62
|
-
function geometricRange(min, max, count, quantum = null) {
|
|
63
|
-
const out = [];
|
|
64
|
-
const ratio = Math.pow(max / min, 1 / (count - 1));
|
|
65
|
-
for (let i = 0; i < count; i++) {
|
|
66
|
-
let v = min * Math.pow(ratio, i);
|
|
67
|
-
if (i === 0)
|
|
68
|
-
v = min;
|
|
69
|
-
if (i === count - 1)
|
|
70
|
-
v = max;
|
|
71
|
-
v = quantize(v, quantum);
|
|
72
|
-
v = Math.max(min, Math.min(max, v));
|
|
73
|
-
out.push(parseFloat(v.toFixed(6)));
|
|
74
|
-
}
|
|
75
|
-
return [...new Set(out)].sort((a, b) => a - b);
|
|
76
|
-
}
|
|
77
57
|
function buildDimension(cfg) {
|
|
78
58
|
const min = Number(cfg.min);
|
|
79
59
|
const max = Number(cfg.max);
|
|
@@ -96,7 +76,10 @@ function buildDimension(cfg) {
|
|
|
96
76
|
};
|
|
97
77
|
}
|
|
98
78
|
const ratio = Math.pow(max / min, 1 / (count - 1));
|
|
99
|
-
const values = geometricRange(min, max, count,
|
|
79
|
+
const values = geometricRange(min, max, count, {
|
|
80
|
+
decimals: 6,
|
|
81
|
+
quantum: Number.isFinite(quantum) && quantum > 0 ? quantum : null,
|
|
82
|
+
});
|
|
100
83
|
return {
|
|
101
84
|
values,
|
|
102
85
|
meta: {
|
|
@@ -245,19 +228,6 @@ function parseArgs(argv = process.argv.slice(2)) {
|
|
|
245
228
|
}
|
|
246
229
|
return out;
|
|
247
230
|
}
|
|
248
|
-
function percentile(values, q) {
|
|
249
|
-
if (!Array.isArray(values) || values.length === 0)
|
|
250
|
-
return null;
|
|
251
|
-
const sorted = [...values].sort((a, b) => a - b);
|
|
252
|
-
const qq = Math.max(0, Math.min(1, q));
|
|
253
|
-
const pos = (sorted.length - 1) * qq;
|
|
254
|
-
const lo = Math.floor(pos);
|
|
255
|
-
const hi = Math.ceil(pos);
|
|
256
|
-
if (lo === hi)
|
|
257
|
-
return sorted[lo];
|
|
258
|
-
const t = pos - lo;
|
|
259
|
-
return sorted[lo] * (1 - t) + sorted[hi] * t;
|
|
260
|
-
}
|
|
261
231
|
function getAmaObjectivesFromArgs(args) {
|
|
262
232
|
const objectives = cloneObjectives();
|
|
263
233
|
for (const o of objectives) {
|
|
@@ -479,36 +449,17 @@ function runSearchShard(payload, onProgress = null) {
|
|
|
479
449
|
return { workerId, entries, totalCombos, validCombos: valid };
|
|
480
450
|
}
|
|
481
451
|
function spawnShardWorker(payload, onProgress) {
|
|
482
|
-
return
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
worker.on('message', (msg) => {
|
|
487
|
-
if (!msg || typeof msg !== 'object')
|
|
488
|
-
return;
|
|
489
|
-
if (msg.type === 'progress') {
|
|
490
|
-
if (onProgress)
|
|
491
|
-
onProgress(msg);
|
|
492
|
-
return;
|
|
452
|
+
return runModuleWorker(import.meta.url, { type: 'search_shard', payload }, {
|
|
453
|
+
onProgress: (msg) => {
|
|
454
|
+
if (msg && typeof msg === 'object' && msg.type === 'progress') {
|
|
455
|
+
onProgress?.(msg);
|
|
493
456
|
}
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
worker.on('exit', (code) => {
|
|
499
|
-
if (code !== 0)
|
|
500
|
-
reject(new Error(`Worker exited with code ${code}`));
|
|
501
|
-
});
|
|
457
|
+
},
|
|
458
|
+
resolveOn: (msg) => msg && typeof msg === 'object' && msg.type === 'done'
|
|
459
|
+
? { done: true, value: msg.result }
|
|
460
|
+
: { done: false },
|
|
502
461
|
});
|
|
503
462
|
}
|
|
504
|
-
function splitIntoShards(values, shardCount) {
|
|
505
|
-
const out = [];
|
|
506
|
-
const size = Math.ceil(values.length / shardCount);
|
|
507
|
-
for (let i = 0; i < values.length; i += size) {
|
|
508
|
-
out.push(values.slice(i, i + size));
|
|
509
|
-
}
|
|
510
|
-
return out.filter((s) => s.length > 0);
|
|
511
|
-
}
|
|
512
463
|
// ── Main ───────────────────────────────────────────────────────────────────────
|
|
513
464
|
async function run() {
|
|
514
465
|
const args = parseArgs();
|
|
@@ -585,7 +536,8 @@ async function run() {
|
|
|
585
536
|
const skipCap = Number.isFinite(args.fixedEr) && Number.isFinite(args.fixedFast);
|
|
586
537
|
const objectiveResults = objectives.map((objective) => {
|
|
587
538
|
const distanceWeight = objective.distanceWeight;
|
|
588
|
-
|
|
539
|
+
// distanceCapQuantile is a fraction in (0, 1]; percentile takes [0, 100].
|
|
540
|
+
const computedCap = skipCap ? null : percentile(maxDistVals, objective.distanceCapQuantile * 100);
|
|
589
541
|
const cappedEntries = skipCap || computedCap == null ? entries : entries.filter((e) => e.area.maxDist <= computedCap);
|
|
590
542
|
let best = null;
|
|
591
543
|
for (const e of cappedEntries) {
|
|
@@ -28,4 +28,16 @@ export declare function baseAnalysisConfig(): AnalysisBaseConfig;
|
|
|
28
28
|
* caller can `continue` to the next token.
|
|
29
29
|
*/
|
|
30
30
|
export declare function consumeCommonAnalysisArg(arg: string, next: () => string, config: AnalysisBaseConfig): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Print the standard analysis-CLI help preamble:
|
|
33
|
+
* `title` / blank / `Usage: node dist/analysis/<usagePath> [options]` / blank /
|
|
34
|
+
* `Options:`. Callers then emit their own option rows (see `helpRow`).
|
|
35
|
+
*/
|
|
36
|
+
export declare function printHelpHeader(title: string, usagePath: string): void;
|
|
37
|
+
/**
|
|
38
|
+
* Render one aligned option row for a hand-written help body:
|
|
39
|
+
* two-space indent, `flag` padded to `width`, then `description`.
|
|
40
|
+
* `width` is per-tool so adopting this helper keeps the original column.
|
|
41
|
+
*/
|
|
42
|
+
export declare function helpRow(flag: string, description: string, width: number): string;
|
|
31
43
|
//# sourceMappingURL=analyze_args.d.ts.map
|
|
@@ -38,4 +38,24 @@ export function consumeCommonAnalysisArg(arg, next, config) {
|
|
|
38
38
|
return false;
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Print the standard analysis-CLI help preamble:
|
|
43
|
+
* `title` / blank / `Usage: node dist/analysis/<usagePath> [options]` / blank /
|
|
44
|
+
* `Options:`. Callers then emit their own option rows (see `helpRow`).
|
|
45
|
+
*/
|
|
46
|
+
export function printHelpHeader(title, usagePath) {
|
|
47
|
+
console.log(title);
|
|
48
|
+
console.log('');
|
|
49
|
+
console.log(`Usage: node dist/analysis/${usagePath} [options]`);
|
|
50
|
+
console.log('');
|
|
51
|
+
console.log('Options:');
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Render one aligned option row for a hand-written help body:
|
|
55
|
+
* two-space indent, `flag` padded to `width`, then `description`.
|
|
56
|
+
* `width` is per-tool so adopting this helper keeps the original column.
|
|
57
|
+
*/
|
|
58
|
+
export function helpRow(flag, description, width) {
|
|
59
|
+
return ` ${flag.padEnd(width)}${description}`;
|
|
60
|
+
}
|
|
41
61
|
//# sourceMappingURL=analyze_args.js.map
|
|
@@ -71,21 +71,6 @@ declare function buildGrid(center: number, params: {
|
|
|
71
71
|
sells: GridOrder[];
|
|
72
72
|
rail: number[];
|
|
73
73
|
};
|
|
74
|
-
/**
|
|
75
|
-
* Mark the held inventory position to `markPrice` in capital units.
|
|
76
|
-
*
|
|
77
|
-
* Carried bags are a REAL risk the drawdown tracker should see bar-by-bar,
|
|
78
|
-
* but their mark is informational for scoring: realized rotation profit plus
|
|
79
|
-
* op fees drive netProfit, and the end-of-run position is reported separately
|
|
80
|
-
* instead of being dumped into totals.
|
|
81
|
-
*/
|
|
82
|
-
declare function markInventoryAtPrice(inventory: {
|
|
83
|
-
units: number;
|
|
84
|
-
cost: number;
|
|
85
|
-
}, exitPrice: number, feeRoundtripPct: number): {
|
|
86
|
-
grossUnits: number;
|
|
87
|
-
profitUnits: number;
|
|
88
|
-
};
|
|
89
74
|
interface SimCandle {
|
|
90
75
|
open?: number;
|
|
91
76
|
high: number;
|
|
@@ -311,5 +296,5 @@ declare function sweepOneAma(strategy: AmaStrategy, candles: SimCandle[], closes
|
|
|
311
296
|
}[];
|
|
312
297
|
evaluated: number;
|
|
313
298
|
};
|
|
314
|
-
export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid,
|
|
299
|
+
export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid, simulatePersistentGrid, sweepOneAma };
|
|
315
300
|
//# sourceMappingURL=backtest_ama_sweep.d.ts.map
|
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import os from 'node:os';
|
|
4
|
-
import { pathToFileURL
|
|
5
|
-
import {
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
6
6
|
import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
|
|
7
7
|
import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
|
|
8
8
|
import { range } from '../math_utils.js';
|
|
9
|
-
import {
|
|
9
|
+
import { runModuleWorker } from '../worker_pool.js';
|
|
10
|
+
import { loadLpData, fmt, loadAmaStrategies, consumeBacktestArg, slopeResetThresholdPct, DEFAULT_FEE_ROUNDTRIP_PCT, DEFAULT_MIN_SPREAD_FACTOR, DEFAULT_BTS_CREATE_FEE, DEFAULT_BTS_CANCEL_FEE, DEFAULT_BTS_MAKER_CREATE_FACTOR, DEFAULT_TX_FEE_PRICE, DEFAULT_REPOSITION_PCT, SLOPE_LOOKBACK_BARS } from './shared_utils.js';
|
|
10
11
|
import { getStorage } from '../../modules/storage/index.js';
|
|
11
12
|
import { PATHS } from '../../modules/paths.js';
|
|
12
|
-
import {
|
|
13
|
+
import { MARKET_ADAPTER } from '../../modules/constants.js';
|
|
13
14
|
// Production grid geometry + slope-ratio offset — shared with bot_fitting so
|
|
14
15
|
// both tools build byte-identical grids for identical params (#12).
|
|
15
16
|
import { buildProductionGrid, computeGridPriceOffsetPct } from './backtest_bot_fitting.js';
|
|
16
|
-
const {
|
|
17
|
+
const { writeJSON } = getStorage();
|
|
17
18
|
/**
|
|
18
19
|
* AMA SWEEP BACKTEST — persistent grid simulation
|
|
19
20
|
*
|
|
@@ -33,14 +34,7 @@ const { readJSON, writeJSON } = getStorage();
|
|
|
33
34
|
* node dist/analysis/bot_fitting/backtest_ama_sweep.js --data <path-to-lp-candles.json> --spread 4:16:1 --increment 0.5:4:0.25
|
|
34
35
|
*/
|
|
35
36
|
const DEFAULT_MAX_ORDERS = 20; // weight-profile sizing cap per side (search abstraction)
|
|
36
|
-
const DEFAULT_FEE_ROUNDTRIP_PCT = 0.20;
|
|
37
|
-
// Canonical spread floor from production grid limits (modules/constants.ts).
|
|
38
|
-
const DEFAULT_MIN_SPREAD_FACTOR = GRID_LIMITS.MIN_SPREAD_FACTOR;
|
|
39
37
|
const DEFAULT_CAPITAL = 10000; // notional units per side
|
|
40
|
-
const DEFAULT_BTS_CREATE_FEE = 0.48260;
|
|
41
|
-
const DEFAULT_BTS_CANCEL_FEE = 0.00482;
|
|
42
|
-
const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.10;
|
|
43
|
-
const DEFAULT_TX_FEE_PRICE = 1.0;
|
|
44
38
|
// Weight profiles (symmetric for both sides)
|
|
45
39
|
// valley: heavier at edges (outer levels), lighter near center
|
|
46
40
|
// neutral: equal across all levels
|
|
@@ -57,14 +51,6 @@ const WEIGHT_PROFILES = {
|
|
|
57
51
|
const DEFAULT_SPREAD_VALUES = [...range(0.5, 4, 0.25), ...range(5, 12, 1)];
|
|
58
52
|
const DEFAULT_INCREMENT_VALUES = [...range(0.2, 2, 0.1), ...range(2.5, 8, 0.5)];
|
|
59
53
|
const DEFAULT_RATIO_VALUES = [1.05, 1.1, 1.15, 1.2, 1.3, 1.5, 2, 3, 5, 10];
|
|
60
|
-
// Reposition threshold: production default (MARKET_ADAPTER
|
|
61
|
-
// AMA_DELTA_THRESHOLD_PERCENT = 1%); --reposition overrides.
|
|
62
|
-
const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
|
|
63
|
-
// Trigger B / grid-price offset (asymmetricBounds whitelist) — same constants
|
|
64
|
-
// as bot_fitting, shared semantics with the live adapter.
|
|
65
|
-
const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
|
|
66
|
-
const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
|
|
67
|
-
const SLOPE_LOOKBACK_BARS = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
|
|
68
54
|
function parseArgs() {
|
|
69
55
|
const args = process.argv.slice(2);
|
|
70
56
|
const out = {
|
|
@@ -99,63 +85,23 @@ function parseArgs() {
|
|
|
99
85
|
}
|
|
100
86
|
if (!val)
|
|
101
87
|
continue;
|
|
88
|
+
if (consumeBacktestArg(arg, val, out, {
|
|
89
|
+
spreadValues: DEFAULT_SPREAD_VALUES,
|
|
90
|
+
incrementValues: DEFAULT_INCREMENT_VALUES,
|
|
91
|
+
ratioValues: DEFAULT_RATIO_VALUES,
|
|
92
|
+
})) {
|
|
93
|
+
i++;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
102
96
|
switch (arg) {
|
|
103
|
-
case '--data':
|
|
104
|
-
out.dataPath = path.resolve(val);
|
|
105
|
-
i++;
|
|
106
|
-
break;
|
|
107
|
-
case '--results':
|
|
108
|
-
out.resultsPath = path.resolve(val);
|
|
109
|
-
i++;
|
|
110
|
-
break;
|
|
111
|
-
case '--spread':
|
|
112
|
-
out.spreadValues = parseListOrRange(val, DEFAULT_SPREAD_VALUES);
|
|
113
|
-
i++;
|
|
114
|
-
break;
|
|
115
|
-
case '--increment':
|
|
116
|
-
out.incrementValues = parseListOrRange(val, DEFAULT_INCREMENT_VALUES);
|
|
117
|
-
i++;
|
|
118
|
-
break;
|
|
119
|
-
case '--ratio':
|
|
120
|
-
out.ratioValues = parseListOrRange(val, DEFAULT_RATIO_VALUES);
|
|
121
|
-
i++;
|
|
122
|
-
break;
|
|
123
97
|
case '--max-orders':
|
|
124
98
|
out.maxOrders = Number(val);
|
|
125
99
|
i++;
|
|
126
100
|
break;
|
|
127
|
-
case '--fee':
|
|
128
|
-
out.feeRoundtripPct = Number(val);
|
|
129
|
-
i++;
|
|
130
|
-
break;
|
|
131
|
-
case '--min-spread-factor':
|
|
132
|
-
out.minSpreadFactor = Number(val);
|
|
133
|
-
i++;
|
|
134
|
-
break;
|
|
135
101
|
case '--capital':
|
|
136
102
|
out.capital = Number(val);
|
|
137
103
|
i++;
|
|
138
104
|
break;
|
|
139
|
-
case '--reposition':
|
|
140
|
-
out.repositionPct = Number(val);
|
|
141
|
-
i++;
|
|
142
|
-
break;
|
|
143
|
-
case '--bts-create-fee':
|
|
144
|
-
out.btsCreateFee = Number(val);
|
|
145
|
-
i++;
|
|
146
|
-
break;
|
|
147
|
-
case '--bts-cancel-fee':
|
|
148
|
-
out.btsCancelFee = Number(val);
|
|
149
|
-
i++;
|
|
150
|
-
break;
|
|
151
|
-
case '--maker-create-factor':
|
|
152
|
-
out.makerCreateFactor = Number(val);
|
|
153
|
-
i++;
|
|
154
|
-
break;
|
|
155
|
-
case '--tx-fee-price':
|
|
156
|
-
out.txFeePrice = Number(val);
|
|
157
|
-
i++;
|
|
158
|
-
break;
|
|
159
105
|
case '--top':
|
|
160
106
|
out.topN = Number(val);
|
|
161
107
|
i++;
|
|
@@ -199,23 +145,6 @@ function printHelp() {
|
|
|
199
145
|
console.log(' --top <n> Show top N results (default: 15)');
|
|
200
146
|
console.log(` --lookback <bars> Huber slope lookback override (default: ${SLOPE_LOOKBACK_BARS})`);
|
|
201
147
|
}
|
|
202
|
-
function loadAmaStrategies(resultsPath) {
|
|
203
|
-
const json = readJSON(resultsPath);
|
|
204
|
-
const amas = json.meta?.amas;
|
|
205
|
-
if (!amas)
|
|
206
|
-
throw new Error('No meta.amas found in results file.');
|
|
207
|
-
const out = [];
|
|
208
|
-
for (const [key, val] of Object.entries(amas)) {
|
|
209
|
-
const v = val;
|
|
210
|
-
if (!v || !Number.isFinite(Number(v.er)))
|
|
211
|
-
continue;
|
|
212
|
-
out.push({ id: key, name: String(v.label || key), er: Number(v.er), fast: Number(v.fast), slow: Number(v.slow) });
|
|
213
|
-
}
|
|
214
|
-
out.sort((a, b) => a.id.localeCompare(b.id));
|
|
215
|
-
if (out.length === 0)
|
|
216
|
-
throw new Error('No valid AMA strategies found');
|
|
217
|
-
return out;
|
|
218
|
-
}
|
|
219
148
|
// ── Order sizing with weight profiles ────────────────────────────────────────
|
|
220
149
|
/**
|
|
221
150
|
* Allocate capital across N levels using weight profile.
|
|
@@ -317,7 +246,7 @@ function simulatePersistentGrid(candles, amaValues, params, weightName, weightFa
|
|
|
317
246
|
const skip = Math.min(warmupParam, Math.max(0, candles.length - 2));
|
|
318
247
|
const capitalPerSide = capital;
|
|
319
248
|
const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
|
|
320
|
-
const slopeDeltaThresholdPct = (
|
|
249
|
+
const slopeDeltaThresholdPct = slopeResetThresholdPct();
|
|
321
250
|
// First tradable bar: need a finite positive AMA to anchor the grid.
|
|
322
251
|
let startIdx = Math.min(skip, candles.length - 1);
|
|
323
252
|
let gridCenter = Number.NaN;
|
|
@@ -753,18 +682,8 @@ function runParallel(strategies, candles, closes, weightEntries, cfg) {
|
|
|
753
682
|
const numCpus = Math.min(os.cpus().length, strategies.length);
|
|
754
683
|
console.log(` Workers: ${numCpus} threads (${os.cpus().length} CPUs available)\n`);
|
|
755
684
|
return Promise.all(strategies.map((strategy) => {
|
|
756
|
-
return
|
|
757
|
-
|
|
758
|
-
// (__filename is undefined in ES modules).
|
|
759
|
-
const worker = new Worker(fileURLToPath(import.meta.url), {
|
|
760
|
-
workerData: { strategy, candles, closes, weightEntries, cfg },
|
|
761
|
-
});
|
|
762
|
-
worker.on('message', (msg) => resolve(msg));
|
|
763
|
-
worker.on('error', reject);
|
|
764
|
-
worker.on('exit', (code) => {
|
|
765
|
-
if (code !== 0)
|
|
766
|
-
reject(new Error(`Worker exited with code ${code}`));
|
|
767
|
-
});
|
|
685
|
+
return runModuleWorker(import.meta.url, { strategy, candles, closes, weightEntries, cfg }, {
|
|
686
|
+
resolveOn: (msg) => ({ done: true, value: msg }),
|
|
768
687
|
});
|
|
769
688
|
}));
|
|
770
689
|
}
|
|
@@ -774,7 +693,7 @@ async function run() {
|
|
|
774
693
|
const loaded = loadLpData(cfg.dataPath);
|
|
775
694
|
const candles = loaded.candles;
|
|
776
695
|
const closes = candles.map((c) => c.close);
|
|
777
|
-
const strategies = loadAmaStrategies(cfg.resultsPath);
|
|
696
|
+
const strategies = loadAmaStrategies(cfg.resultsPath, { sort: true });
|
|
778
697
|
const weightEntries = Object.entries(WEIGHT_PROFILES);
|
|
779
698
|
const totalCombos = cfg.spreadValues.length * cfg.incrementValues.length *
|
|
780
699
|
cfg.ratioValues.length * weightEntries.length;
|
|
@@ -791,7 +710,7 @@ async function run() {
|
|
|
791
710
|
console.log(` Spread floor: > fee (${cfg.feeRoundtripPct}%)`);
|
|
792
711
|
console.log(` Reset (A): ${cfg.repositionPct}% AMA drift from grid center (ratchet)`);
|
|
793
712
|
console.log(` Asym. bounds: ${cfg.asymmetricBounds ? 'ON — slope reset (B) + grid price offset enabled (whitelist semantics)' : 'OFF — typical non-whitelisted bot (production default)'}`);
|
|
794
|
-
console.log(` Reset (B): |slope - slope@lastReset| >= ${fmt((
|
|
713
|
+
console.log(` Reset (B): |slope - slope@lastReset| >= ${fmt(slopeResetThresholdPct(), 4)}% (lookback ${cfg.lookbackBars ?? SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
|
|
795
714
|
console.log(` Tx model: create=${fmt(cfg.btsCreateFee, 5)} BTS, cancel=${fmt(cfg.btsCancelFee, 5)} BTS, maker=${fmt(cfg.makerCreateFactor * 100, 1)}%, 1 BTS=${fmt(cfg.txFeePrice, 2)} units`);
|
|
796
715
|
console.log(` Combos/AMA: ${totalCombos} | Total: ${totalCombos * strategies.length}\n`);
|
|
797
716
|
// ── Run AMA sweeps in parallel (one worker per AMA strategy) ──────
|
|
@@ -971,5 +890,5 @@ async function run() {
|
|
|
971
890
|
if (isMainThread && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
972
891
|
run().catch((err) => { console.error(err); process.exit(1); });
|
|
973
892
|
}
|
|
974
|
-
export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid,
|
|
893
|
+
export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid, simulatePersistentGrid, sweepOneAma };
|
|
975
894
|
//# sourceMappingURL=backtest_ama_sweep.js.map
|
|
@@ -6,25 +6,23 @@ import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strate
|
|
|
6
6
|
import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
|
|
7
7
|
import { applyAsymmetricBounds } from '../../market_adapter/core/asymmetric_bounds.js';
|
|
8
8
|
import { range } from '../math_utils.js';
|
|
9
|
-
import {
|
|
9
|
+
import { loadLpData, fmt, loadAmaStrategies, consumeBacktestArg, slopeResetThresholdPct, DEFAULT_FEE_ROUNDTRIP_PCT, DEFAULT_MIN_SPREAD_FACTOR, DEFAULT_BTS_CREATE_FEE, DEFAULT_BTS_CANCEL_FEE, DEFAULT_BTS_MAKER_CREATE_FACTOR, DEFAULT_TX_FEE_PRICE, DEFAULT_REPOSITION_PCT, SLOPE_TRIGGER_FACTOR, SLOPE_MAX_PCT, SLOPE_LOOKBACK_BARS } from './shared_utils.js';
|
|
10
10
|
import { getStorage } from '../../modules/storage/index.js';
|
|
11
11
|
import { PATHS } from '../../modules/paths.js';
|
|
12
12
|
import { GRID_LIMITS, MARKET_ADAPTER } from '../../modules/constants.js';
|
|
13
|
-
const { ensureDir,
|
|
13
|
+
const { ensureDir, writeJSON } = getStorage();
|
|
14
14
|
// Default mirrors production sizing: createOrderGrid sizes EVERY rail slot in
|
|
15
15
|
// bounds (modules/order/grid.ts), it does not cap per side. Infinity = all
|
|
16
16
|
// slots; --active-orders N restores a bounded run.
|
|
17
17
|
const DEFAULT_ACTIVE_ORDERS = Infinity;
|
|
18
|
-
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.10;
|
|
27
|
-
const DEFAULT_TX_FEE_PRICE = 1.0;
|
|
18
|
+
// BTS operation fees are shared with backtest_ama_sweep via shared_utils; the
|
|
19
|
+
// fee-capital base (the notional the fee percentage is measured against) is
|
|
20
|
+
// bot_fitting-specific.
|
|
21
|
+
//
|
|
22
|
+
// Every placement (initial grid, reset rebuild, per-cycle slot refill) pays a
|
|
23
|
+
// maker create fee, every cancel pays a cancel fee. Fees are converted into
|
|
24
|
+
// percentage points against --bts-fee-capital so they deduct from net capture
|
|
25
|
+
// in the same units as the rest of the accounting.
|
|
28
26
|
const DEFAULT_BTS_FEE_CAPITAL = 10000;
|
|
29
27
|
// ── Production grid-reset triggers (MARKET_ADAPTER, modules/constants.ts) ────
|
|
30
28
|
//
|
|
@@ -33,7 +31,6 @@ const DEFAULT_BTS_FEE_CAPITAL = 10000;
|
|
|
33
31
|
// from that recorded center; the center re-records only when a trigger fires
|
|
34
32
|
// (ratchet semantics — see analyze_ama_price_changes.trackRepositions).
|
|
35
33
|
// --reposition-pct overrides the default.
|
|
36
|
-
const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
|
|
37
34
|
//
|
|
38
35
|
// Trigger B — AMA slope delta, plus the grid price offset, are BOTH gated in
|
|
39
36
|
// production behind the per-bot asymmetricBounds whitelist
|
|
@@ -47,16 +44,11 @@ const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
|
|
|
47
44
|
// where slopePct is the Huber-robust per-bar AMA slope over
|
|
48
45
|
// DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeHuberWindowSlopePct) and the
|
|
49
46
|
// baseline mirrors botState.gridRangeScalingAmaSlope (re-seeded every reset).
|
|
50
|
-
const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
|
|
51
|
-
const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
|
|
52
|
-
const SLOPE_LOOKBACK_BARS = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
|
|
53
47
|
const SLOPE_NEUTRAL_ZONE_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
|
|
54
48
|
// Spread-gap floor knobs (GRID_LIMITS): the effective target spread is
|
|
55
49
|
// clamped up to incrementPercent × MIN_SPREAD_FACTOR and the gap is never
|
|
56
50
|
// narrower than MIN_SPREAD_ORDERS slots — mirrored from calculateGapSlots
|
|
57
51
|
// (modules/order/utils/math.ts).
|
|
58
|
-
const DEFAULT_MIN_SPREAD_FACTOR = GRID_LIMITS.MIN_SPREAD_FACTOR;
|
|
59
|
-
// Inventory-risk penalty weights (in score points)
|
|
60
52
|
const RISK_W_DURATION = 1.0; // avg open bars
|
|
61
53
|
const RISK_W_PEAK_OPEN = 2.0; // peak simultaneous open orders
|
|
62
54
|
const RISK_W_IMBALANCE = 1.2; // avg |openBuy-openSell|
|
|
@@ -98,59 +90,19 @@ function parseArgs() {
|
|
|
98
90
|
const val = args[i + 1];
|
|
99
91
|
if (!val)
|
|
100
92
|
continue;
|
|
93
|
+
if (consumeBacktestArg(arg, val, out, {
|
|
94
|
+
spreadValues: DEFAULT_SPREAD_VALUES,
|
|
95
|
+
incrementValues: DEFAULT_INCREMENT_VALUES,
|
|
96
|
+
ratioValues: DEFAULT_RATIO_VALUES,
|
|
97
|
+
})) {
|
|
98
|
+
i++;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
101
|
switch (arg) {
|
|
102
|
-
case '--data':
|
|
103
|
-
out.dataPath = path.resolve(val);
|
|
104
|
-
i++;
|
|
105
|
-
break;
|
|
106
|
-
case '--results':
|
|
107
|
-
out.resultsPath = path.resolve(val);
|
|
108
|
-
i++;
|
|
109
|
-
break;
|
|
110
|
-
case '--spread':
|
|
111
|
-
out.spreadValues = parseListOrRange(val, DEFAULT_SPREAD_VALUES);
|
|
112
|
-
i++;
|
|
113
|
-
break;
|
|
114
|
-
case '--increment':
|
|
115
|
-
out.incrementValues = parseListOrRange(val, DEFAULT_INCREMENT_VALUES);
|
|
116
|
-
i++;
|
|
117
|
-
break;
|
|
118
|
-
case '--ratio':
|
|
119
|
-
out.ratioValues = parseListOrRange(val, DEFAULT_RATIO_VALUES);
|
|
120
|
-
i++;
|
|
121
|
-
break;
|
|
122
102
|
case '--active-orders':
|
|
123
103
|
out.activeOrders = Number(val);
|
|
124
104
|
i++;
|
|
125
105
|
break;
|
|
126
|
-
case '--fee':
|
|
127
|
-
out.feeRoundtripPct = Number(val);
|
|
128
|
-
i++;
|
|
129
|
-
break;
|
|
130
|
-
case '--min-spread-factor':
|
|
131
|
-
out.minSpreadFactor = Number(val);
|
|
132
|
-
i++;
|
|
133
|
-
break;
|
|
134
|
-
case '--reposition-pct':
|
|
135
|
-
out.repositionPct = Number(val);
|
|
136
|
-
i++;
|
|
137
|
-
break;
|
|
138
|
-
case '--bts-create-fee':
|
|
139
|
-
out.btsCreateFee = Number(val);
|
|
140
|
-
i++;
|
|
141
|
-
break;
|
|
142
|
-
case '--bts-cancel-fee':
|
|
143
|
-
out.btsCancelFee = Number(val);
|
|
144
|
-
i++;
|
|
145
|
-
break;
|
|
146
|
-
case '--maker-create-factor':
|
|
147
|
-
out.makerCreateFactor = Number(val);
|
|
148
|
-
i++;
|
|
149
|
-
break;
|
|
150
|
-
case '--tx-fee-price':
|
|
151
|
-
out.txFeePrice = Number(val);
|
|
152
|
-
i++;
|
|
153
|
-
break;
|
|
154
106
|
case '--bts-fee-capital':
|
|
155
107
|
out.btsFeeCapital = Number(val);
|
|
156
108
|
i++;
|
|
@@ -217,28 +169,6 @@ function resolveAutoResultsPath(dataPath) {
|
|
|
217
169
|
return newest.file;
|
|
218
170
|
return path.join(PATHS.ANALYSIS.RESULTS_DIR, `optimization_results_${base}.json`);
|
|
219
171
|
}
|
|
220
|
-
function loadAmaStrategies(resultsPath) {
|
|
221
|
-
const json = readJSON(resultsPath);
|
|
222
|
-
const amas = json.meta?.amas ?? {};
|
|
223
|
-
const labels = { AMA1: 'AMA1', AMA2: 'AMA2', AMA3: 'AMA3', AMA4: 'AMA4' };
|
|
224
|
-
const out = [];
|
|
225
|
-
for (const [key, val] of Object.entries(amas)) {
|
|
226
|
-
const a = val;
|
|
227
|
-
if (!a || !Number.isFinite(Number(a.er)) || !Number.isFinite(Number(a.fast)) || !Number.isFinite(Number(a.slow)))
|
|
228
|
-
continue;
|
|
229
|
-
out.push({
|
|
230
|
-
id: key,
|
|
231
|
-
name: labels[key] ?? key,
|
|
232
|
-
er: Number(a.er),
|
|
233
|
-
fast: Number(a.fast),
|
|
234
|
-
slow: Number(a.slow),
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
if (out.length !== 4) {
|
|
238
|
-
throw new Error(`Expected 4 AMA strategies in results meta.amas, found ${out.length}`);
|
|
239
|
-
}
|
|
240
|
-
return out;
|
|
241
|
-
}
|
|
242
172
|
/**
|
|
243
173
|
* Spread-gap width in slots — direct port of calculateGapSlots
|
|
244
174
|
* (modules/order/utils/math.ts:1228). The effective target spread is clamped
|
|
@@ -343,7 +273,7 @@ function simulateForParams(candles, amaValues, params) {
|
|
|
343
273
|
// start on SMA-warmup values when the fitted ER period is large.
|
|
344
274
|
const skip = Math.min(params.warmupBars, Math.max(0, candles.length - 2));
|
|
345
275
|
const singleLegFeePct = feeRoundtripPct / 2;
|
|
346
|
-
const slopeDeltaThresholdPct = (
|
|
276
|
+
const slopeDeltaThresholdPct = slopeResetThresholdPct();
|
|
347
277
|
const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
|
|
348
278
|
const stepUpFrac = 1 + incrementPct; // one-rail-step rotation distance
|
|
349
279
|
// Optional gate/band overrides. `slopePersistBars` follows the production
|
|
@@ -696,7 +626,11 @@ function run() {
|
|
|
696
626
|
const loaded = loadLpData(cfg.dataPath);
|
|
697
627
|
const candles = loaded.candles;
|
|
698
628
|
const closes = candles.map((c) => c.close);
|
|
699
|
-
const strategies = loadAmaStrategies(cfg.resultsPath
|
|
629
|
+
const strategies = loadAmaStrategies(cfg.resultsPath, {
|
|
630
|
+
requireAllFields: true,
|
|
631
|
+
exactCount: 4,
|
|
632
|
+
labels: { AMA1: 'AMA1', AMA2: 'AMA2', AMA3: 'AMA3', AMA4: 'AMA4' },
|
|
633
|
+
});
|
|
700
634
|
if (!Number.isFinite(cfg.repositionPct) || cfg.repositionPct <= 0) {
|
|
701
635
|
throw new Error(`Invalid reposition threshold: ${cfg.repositionPct}`);
|
|
702
636
|
}
|
|
@@ -714,7 +648,7 @@ function run() {
|
|
|
714
648
|
console.log(` Spread floor: spread >= ${cfg.minSpreadFactor} x increment`);
|
|
715
649
|
console.log(` Reset (A): AMA drift >= ${cfg.repositionPct}% from recorded center${cfg.repositionPct === DEFAULT_REPOSITION_PCT ? ' (AMA_DELTA_THRESHOLD_PERCENT)' : ''}`);
|
|
716
650
|
console.log(` Asym. bounds: ${cfg.asymmetricBounds ? 'ON — slope reset (B) + grid price offset enabled (whitelist semantics)' : 'OFF — typical non-whitelisted bot (production default)'}`);
|
|
717
|
-
console.log(` Reset (B): |slope - slope@lastReset| >= ${(
|
|
651
|
+
console.log(` Reset (B): |slope - slope@lastReset| >= ${slopeResetThresholdPct()}% (${SLOPE_TRIGGER_FACTOR}% x ${SLOPE_MAX_PCT}, lookback ${SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
|
|
718
652
|
console.log(` Tx fees: create=${fmt(cfg.btsCreateFee * cfg.makerCreateFactor, 5)} BTS, cancel=${fmt(cfg.btsCancelFee, 5)} BTS, 1 BTS=${fmt(cfg.txFeePrice, 2)} units, capital=${fmt(cfg.btsFeeCapital, 0)}`);
|
|
719
653
|
console.log(` Risk W: duration=${cfg.riskWDuration}, peakOpen=${cfg.riskWPeakOpen}, imbalance=${cfg.riskWImbalance}, cancel=${cfg.riskWCancel}`);
|
|
720
654
|
console.log(` Combos/AMA: ${totalCombos}\n`);
|
|
@@ -810,7 +744,7 @@ function run() {
|
|
|
810
744
|
baseScore: 'totalNetCaptureAfterFeesPct * (fillEfficiency / 100)',
|
|
811
745
|
gridModel: 'persistent fixed chain prices (createOrderGrid port): master rail at sqrt(1±inc) offsets bounded by [center/ratio, center*ratio], gapSlots spread zone centered on center; prices never follow AMA after placement',
|
|
812
746
|
spreadParam: 'targetSpreadPercent for calculateGapSlots (floored at increment * MIN_SPREAD_FACTOR)',
|
|
813
|
-
resetTriggers: `(A) AMA drift >= ${cfg.repositionPct}% from recorded center (ratchet)${cfg.asymmetricBounds ? ` OR (B) |slope - slopeAtLastReset| >= ${(
|
|
747
|
+
resetTriggers: `(A) AMA drift >= ${cfg.repositionPct}% from recorded center (ratchet)${cfg.asymmetricBounds ? ` OR (B) |slope - slopeAtLastReset| >= ${slopeResetThresholdPct()}% over ${SLOPE_LOOKBACK_BARS}-bar average slope (baseline re-seeded on every reset)` : ' (trigger B gated off — asymmetricBounds whitelist)'}`,
|
|
814
748
|
gridPriceOffset: cfg.asymmetricBounds ? 'slope-ratio offset applied to placement center (direction * min(|slope|/maxSlopePct,1) * targetSpread/2) on every grid build' : 'disabled (asymmetricBounds whitelist)',
|
|
815
749
|
repositionAccounting: 'unfilled orders canceled + counted (incl armed refills/rebids); bought-and-held base carries across resets in a weighted-average-entry inventory pool (resync never market-sells); end-of-run inventory mark is informational and excluded from scoring',
|
|
816
750
|
cycleEconomics: 'slot rotation: filled buy re-offers one rail step up; that refill selling books ~increment% minus round-trip fee and the freed quote re-bids one step down; unlinked initial-grid sells only execute against held inventory at weighted-average entry (no shorting)',
|