-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdexbot.js
More file actions
executable file
·815 lines (744 loc) · 31.6 KB
/
dexbot.js
File metadata and controls
executable file
·815 lines (744 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
#!/usr/bin/env node
/**
* dexbot.js - DEXBot2 Primary CLI Driver
*
* Main entry point for DEXBot2 grid trading bot system.
* Manages tracked bots and provides helper utilities (key/bot editors).
* Creates grid-based limit orders across price ranges and auto-replaces fills.
*
* ===============================================================================
* FEATURES
* ===============================================================================
*
* GRID TRADING:
* - Configurable grid spacing with geometric increments (e.g., 0.5%)
* - Independent BUY and SELL order counts per bot
* - Dynamic spread zone around market price
* - Automatic order replacement when fills occur
* - Fund allocation controls (percentage of wallet)
* - Copy-on-Write rebalancing: Safe concurrent updates with isolated working grids
* - Automatic grid reconciliation: Detects offline fills and syncs with blockchain
*
* SECURITY:
* - Master password encryption for stored private keys (AES-256-GCM)
* - Optional credential daemon for multi-bot key management
* - No private keys in environment variables
* - Per-bot configuration and state isolation
*
* OPERATION MODES:
* - Live trading: Real orders on blockchain
* - Dry-run mode: Simulate operations without broadcasting
* - Manual control: Enable/disable/reset individual bots
*
* ===============================================================================
* CLI COMMANDS
* ===============================================================================
*
* TRADING OPERATIONS:
* node dexbot start <bot-name> - Start single bot directly (live trading)
* node dexbot drystart <bot-name> - Start bot in dry-run mode (no transactions)
*
* BOT MANAGEMENT:
* node dexbot reset <bot-name> - Reset bot grid (full regeneration)
* node dexbot disable <bot-name> - Mark bot inactive in config
*
* CONFIGURATION:
* node dexbot keys - Manage encryption keys and master password
* node dexbot bots - Interactive editor for bot definitions
*
* PM2 ORCHESTRATION:
* node dexbot pm2 - Start all bots via PM2 with daemon
* node dexbot pm2 unlock-start - Same as above (explicit)
* node dexbot pm2 stop all - Stop all PM2 bot processes
* node dexbot pm2 stop <bot-name> - Stop specific bot
* node dexbot pm2 delete all - Delete all bots from PM2
* node dexbot pm2 delete <bot-name>- Delete specific bot from PM2
* node dexbot pm2 help - Show PM2 command help
*
* MAINTENANCE:
* node dexbot update - Update to latest version (pull + install + restart)
* node dexbot export <bot-name> - Export trading history to CSV/JSON for QTradeX
* node dexbot help - Show this help message
*
* NPM SCRIPTS (alternative invocation):
* npm run pm2:unlock-start - Same as 'node dexbot pm2'
* npm run pm2:start - Start bots (requires ecosystem.config.js pre-generated)
* npm run pm2:stop - Stop all PM2 bots
* npm run pm2:reload - Reload all PM2 bots
*
* ===============================================================================
* CONFIGURATION
* ===============================================================================
*
* Bots: profiles/bots.json
* Keys: profiles/keys.json (gitignored, encrypted)
* State: profiles/orders/{botKey}.json (per-bot grid snapshots)
* Logs: profiles/logs/{botname}.log (managed by PM2)
*
* ===============================================================================
*/
const { BitShares, waitForConnected, setSuppressConnectionLog } = require('./modules/bitshares_client');
const fs = require('fs');
const path = require('path');
const chainKeys = require('./modules/chain_keys');
const { initializeFeeCache, ensureProfilesDirectory } = require('./modules/order/utils/system');
const accountBots = require('./modules/account_bots');
const SharedDEXBot = require('./modules/dexbot_class');
const { authenticateWithChainKeys } = require('./modules/dexbot_class');
const { setupGracefulShutdown, registerCleanup } = require('./modules/graceful_shutdown');
const {
collectValidationIssues,
loadSettingsFile,
normalizeBotEntries,
resolveRawBotEntries,
saveSettingsFile,
} = require('./modules/bot_settings');
// Setup graceful shutdown handlers
setupGracefulShutdown();
// Note: accountOrders is now per-bot only. Each bot has its own AccountOrders instance
// created in DEXBot.start() in modules/dexbot_class.js. This eliminates shared-file race conditions.
// Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
const PROFILES_BOTS_FILE = path.join(__dirname, 'profiles', 'bots.json');
const PROFILES_DIR = path.join(__dirname, 'profiles');
const CLI_COMMANDS = ['start', 'reset', 'disable', 'drystart', 'keys', 'bots', 'pm2', 'update', 'export'];
const CLI_HELP_FLAGS = ['-h', '--help'];
const CLI_EXAMPLES_FLAG = '--cli-examples';
const CLI_EXAMPLES = [
{ title: 'Start a bot from the tracked config', command: 'dexbot start bot-name', notes: 'Targets the named entry in profiles/bots.json.' },
{ title: 'Dry-run a bot without broadcasting', command: 'dexbot drystart bot-name', notes: 'Forces the run into dry-run mode even if the stored config was live.' },
{ title: 'Disable a bot in config', command: 'dexbot disable bot-name', notes: 'Marks the bot inactive in config.' },
{ title: 'Reset a bot grid', command: 'dexbot reset bot-name', notes: 'Triggers a full grid regeneration for the named bot.' },
{ title: 'Manage keys', command: 'dexbot keys', notes: 'Runs modules/chain_keys.js to add or update master passwords.' },
{ title: 'Edit bot definitions', command: 'dexbot bots', notes: 'Launches the interactive modules/account_bots.js helper for the JSON config.' },
{ title: 'Start bots with PM2', command: 'dexbot pm2', notes: 'Generates ecosystem config, authenticates, and starts PM2.' },
{ title: 'Update DEXBot2', command: 'node dexbot update', notes: 'Fetches latest code, updates dependencies, and reloads PM2.' },
{ title: 'Export bot trades for QTradeX', command: 'dexbot export bot-name', notes: 'Exports trading history and settings to CSV/JSON for backtesting.' }
];
const cliArgs = process.argv.slice(2);
/**
* Show the CLI usage/help text when requested or upon invalid commands.
*/
function printCLIUsage() {
console.log('Usage: dexbot [command] [bot-name]');
console.log('Commands:');
console.log(' start <bot> Start the named bot using the tracked config.');
console.log(' drystart <bot> Same as start but forces dry-run execution.');
console.log(' reset <bot> Trigger a grid reset (auto-reloads if running, or applies on next start).');
console.log(' disable <bot> Mark the bot inactive in config.');
console.log(' export <bot> Export bot trades and settings for QTradeX backtesting.');
console.log(' keys Launch the chain key helper (modules/chain_keys.js).');
console.log(' bots Launch the interactive bot configurator (modules/account_bots.js).');
console.log(' pm2 Start all active bots with PM2 (authenticate + generate config + start).');
console.log(' update Update DEXBot2 from the repository and reload active bots.');
console.log('Options:');
console.log(' --cli-examples Print curated CLI snippets.');
console.log(' -h, --help Show this help text.');
console.log('Envs: OPEN_ORDERS_SYNC_LOOP_MS controls the open-orders sync polling delay; LIVE_BOT_NAME or BOT_NAME selects a single entry.');
}
/**
* Print curated CLI snippets for quick reference.
*/
function printCLIExamples() {
console.log('CLI Examples:');
CLI_EXAMPLES.forEach((example, index) => {
console.log(`${index + 1}. ${example.title}`);
console.log(` ${example.command}`);
if (example.notes) console.log(` ${example.notes}`);
});
console.log(`Read the README “CLI usage” section for more details (file: ${PROFILES_BOTS_FILE}).`);
}
if (cliArgs.some(arg => CLI_HELP_FLAGS.includes(arg))) {
printCLIUsage();
process.exit(0);
}
if (cliArgs.includes(CLI_EXAMPLES_FLAG)) {
printCLIExamples();
process.exit(0);
}
// Connection handled centrally by modules/bitshares_client; use waitForConnected() when needed
/**
* DEXBot - Core trading bot class that manages grid-based market making
*
* Responsibilities:
* - Initializes connection to BitShares and authenticates account
* - Creates and manages an OrderManager instance for grid operations
* - Places initial orders and listens for fills to replace them
* - Handles grid synchronization with on-chain state
* - Supports dry-run mode for testing without broadcasting
*
* @class
*/
// Extend SharedDEXBot for dexbot.js context (currently just a thin wrapper)
class DEXBot extends SharedDEXBot {
constructor(config) {
super(config, { logPrefix: '' });
}
}
// Register BitShares cleanup on shutdown
registerCleanup('BitShares connection', () => {
try {
BitShares.disconnect();
} catch (err) {
// BitShares may already be disconnected
}
});
// Track attempts to prevent infinite loops while allowing retries after key setup
let keySetupInProgress = false;
/**
* Launch the account key manager helper.
* @param {Object} [options={}] - Manager options.
* @param {boolean} [options.waitForConnection=false] - Whether to wait for BitShares connection.
* @param {boolean} [options.exitAfter=false] - Whether to exit the process after completion.
* @param {boolean} [options.disconnectAfter=false] - Whether to disconnect BitShares after completion.
* @returns {Promise<void>}
*/
async function runAccountManager({ waitForConnection = false, exitAfter = false, disconnectAfter = false } = {}) {
if (waitForConnection) {
try {
await waitForConnected();
} catch (err) {
console.warn('Timed out waiting for BitShares connection before launching key manager.');
}
}
let succeeded = false;
try {
await chainKeys.main();
succeeded = true;
} finally {
if (disconnectAfter) {
try {
BitShares.disconnect();
} catch (err) {
console.warn('Failed to disconnect BitShares connection after key manager exited:', err.message || err);
}
}
}
if (exitAfter && succeeded) {
process.exit(0);
}
}
/**
* Handle master password authentication with auto-launch fallback.
* If no master password is set, automatically launches the key manager
* to guide the user through initial setup.
* @returns {Promise<string>} The authenticated master password
*/
async function authenticateMasterPassword() {
try {
return await chainKeys.authenticate();
} catch (err) {
if (!keySetupInProgress && err && err.message && err.message.includes('No master password set')) {
keySetupInProgress = true;
try {
await runAccountManager();
keySetupInProgress = false;
return await chainKeys.authenticate();
} catch (setupErr) {
keySetupInProgress = false;
throw setupErr;
}
}
throw err;
}
}
function printStartLauncherHeader({ botName = null, dryRun = false } = {}) {
console.log('='.repeat(50));
console.log('DEXBot2 Start Launcher');
if (botName) {
console.log(`Starting bot: ${botName}`);
} else {
console.log('Starting all bots');
}
if (dryRun) {
console.log('Dry-run mode enabled');
}
console.log('='.repeat(50));
console.log();
}
function printStartLauncherSuccess({ botName = null, dryRun = false } = {}) {
const command = dryRun ? 'drystart' : 'start';
const target = botName ? ` ${botName}` : '';
console.log();
console.log('='.repeat(50));
console.log('DEXBot2 started successfully!');
if (botName) {
console.log(`If the bot stops, rerun \`node dexbot ${command}${target}\` to start it again.`);
} else {
console.log(`If the bots stop, rerun \`node dexbot ${command}\` to start them again.`);
}
console.log('='.repeat(50));
console.log();
}
function printMasterPasswordFailure(err) {
console.error();
console.error(`❌ ${err.message}`);
}
/**
* Execute the provided bot entries after validation and authentication.
* This is the main orchestration function that:
* 1. Validates all bot configurations
* 2. Prompts for master password if any bot needs it
* 3. Creates DEXBot instances and starts them
*
* @param {Array} botEntries - Array of normalized bot configurations
* @param {Object} options - Execution options
* @param {boolean} options.forceDryRun - Force all bots into dry-run mode
* @param {string} options.sourceName - Source label for logging
* @returns {Promise<Array>} Array of started DEXBot instances
*/
async function runBotInstances(botEntries, { forceDryRun = false, sourceName = 'settings', launcherStyle = null } = {}) {
setSuppressConnectionLog(true);
const shouldAnnounceLauncher = !!launcherStyle;
const launcherBotName = launcherStyle?.botName || null;
const launcherDryRun = !!launcherStyle?.dryRun;
let connectionAnnounced = false;
let authenticationAnnounced = false;
const activeCount = (botEntries || []).filter((entry) => entry && entry.active !== false).length;
const announceConnection = () => {
if (shouldAnnounceLauncher && !connectionAnnounced) {
console.log('Connected to BitShares');
connectionAnnounced = true;
}
};
const announceAuthentication = () => {
if (shouldAnnounceLauncher && !authenticationAnnounced) {
console.log('✓ Authentication successful');
authenticationAnnounced = true;
}
};
try {
if (shouldAnnounceLauncher) {
printStartLauncherHeader({ botName: launcherBotName, dryRun: launcherDryRun });
}
if (!botEntries.length) {
console.log(`No bot entries were found in ${sourceName}.`);
return [];
}
const prepared = botEntries.map(entry => ({
...entry,
dryRun: forceDryRun ? true : entry.dryRun,
}));
// Note: ensureBotEntries is no longer needed here. Each bot creates its own AccountOrders
// instance with per-bot file when it starts, eliminating the need for shared initialization.
const { errors } = collectValidationIssues(prepared, sourceName);
if (errors.length) {
console.error('ERROR: Invalid configuration for one or more **active** bots:');
errors.forEach(e => console.error(' -', e));
console.error('Fix the configuration problems in profiles/bots.json and restart. Aborting.');
process.exit(1);
}
const needMaster = prepared.some(b => b.active && b.preferredAccount);
let masterPassword = null;
if (needMaster) {
const daemonReady = chainKeys.isDaemonReady();
try {
await waitForConnected();
announceConnection();
} catch (err) {
// Continue; the bot startup path will retry through the normal runtime flow.
}
if (!daemonReady) {
try {
masterPassword = await authenticateMasterPassword();
announceAuthentication();
} catch (err) {
if (chainKeys.isMasterPasswordFailure(err)) {
throw err;
}
masterPassword = null;
}
}
}
// Fee cache is required for fill processing (getAssetFees), including offline fill reconciliation at startup.
// Initialize it once per process for the assets used by active bots.
try {
await waitForConnected();
announceConnection();
await initializeFeeCache(prepared.filter(b => b.active), BitShares);
} catch (err) {
console.error(`Fee cache initialization failed: ${err.message}`);
console.error('Cannot proceed without fee cache for fill processing. Aborting.');
process.exit(1);
}
if (shouldAnnounceLauncher) {
console.log(`Number active bots: ${activeCount}`);
console.log();
console.log('Starting bot runtime...');
}
const instances = [];
for (const entry of prepared) {
if (!entry.active) {
continue;
}
try {
const bot = new DEXBot(entry);
await bot.start(masterPassword);
instances.push(bot);
} catch (err) {
if (chainKeys.isMasterPasswordFailure(err)) {
printMasterPasswordFailure(err);
process.exit(1);
return;
}
console.error('Failed to start bot:', err.message);
if (err && err.message && String(err.message).toLowerCase().includes('marketprice')) {
console.info('Hint: startPrice could not be derived.');
console.info(' - If using profiles/bots.json with "pool" or "market" signals, ensure the chain contains a matching liquidity pool or orderbook for the configured pair.');
console.info(' - Alternatively, set a numeric `startPrice` directly in profiles/bots.json for this bot to avoid auto-derive.');
console.info(' - You can also set LIVE_BOT_NAME or BOT_NAME to select a different bot from the profiles settings.');
}
}
}
if (instances.length === 0) {
console.log('No active bots were started. Check bots.json and ensure at least one bot is active.');
return instances;
}
if (shouldAnnounceLauncher) {
printStartLauncherSuccess({ botName: launcherBotName, dryRun: launcherDryRun });
}
return instances;
} finally {
setSuppressConnectionLog(false);
}
}
/**
* Start a specific bot by name or all active bots if no name provided.
* Looks up the bot in profiles/bots.json and starts it.
* @param {string|null} botName - Name of the bot to start, or null for all active
* @param {Object} options - Start options
* @param {boolean} options.dryRun - Run in dry-run mode (no broadcasts)
*/
async function startBotByName(botName, { dryRun = false } = {}) {
if (!botName) {
return runDefaultBots({
forceDryRun: dryRun,
sourceName: dryRun ? 'CLI drystart (all)' : 'CLI start (all)',
launcherStyle: { botName: null, dryRun },
});
}
const { config } = loadSettingsFile(PROFILES_BOTS_FILE);
const entries = resolveRawBotEntries(config);
if (!entries.length) {
console.error('No bot definitions exist in the tracked settings.');
process.exit(1);
}
const match = entries.find(b => b.name === botName);
if (!match) {
console.error(`Could not find any bot named '${botName}' in the tracked settings.`);
process.exit(1);
}
const entryCopy = JSON.parse(JSON.stringify(match));
entryCopy.active = true;
if (dryRun) entryCopy.dryRun = true;
const normalized = normalizeBotEntries([entryCopy]);
await runBotInstances(normalized, {
forceDryRun: dryRun,
sourceName: dryRun ? 'CLI drystart' : 'CLI start',
launcherStyle: { botName, dryRun },
});
}
/**
* Mark a bot (or all bots) as inactive in profiles/bots.json.
* Note: This only updates the config file; running processes must be
* stopped separately using pm2.js or Ctrl+C.
* @param {string|null} botName - Name of the bot to disable, or null for all
*/
async function disableBotByName(botName) {
const { config, filePath } = loadSettingsFile(PROFILES_BOTS_FILE);
const entries = resolveRawBotEntries(config);
if (!botName) {
let updated = false;
entries.forEach(entry => {
if (entry.active) {
entry.active = false;
updated = true;
}
});
if (!updated) {
console.log('No active bots were found to disable.');
return;
}
saveSettingsFile(config, filePath);
console.log(`Marked all bots inactive in ${path.basename(filePath)}.`);
return;
}
const match = entries.find(b => b.name === botName);
if (!match) {
console.error(`Could not find any bot named '${botName}' to disable.`);
process.exit(1);
}
if (!match.active) {
console.log(`Bot '${botName}' is already inactive.`);
return;
}
match.active = false;
saveSettingsFile(config, filePath);
console.log(`Marked '${botName}' inactive in ${path.basename(filePath)}. Stop the PM2 process using 'node pm2 stop ${botName}'.`);
}
/**
* Reset a bot by regenerating its grid and starting it fresh.
* This method creates a trigger file that signals the bot instance
* (whether running locally or via PM2) to perform a full grid resync.
*
* 1. Creates profiles/recalculate.<botKey>.trigger
* 2. If bot is running, it detects file -> resyncs grid -> deletes file
* 3. If bot is stopped, it detects file on startup -> resyncs grid -> deletes file
*
* @param {string|null} botName - Name of the bot to reset, or null for all active
*/
async function resetBotByName(botName) {
const { config } = loadSettingsFile(PROFILES_BOTS_FILE);
const entries = normalizeBotEntries(resolveRawBotEntries(config));
// Filter targets
const targets = botName ? entries.filter(b => b.name === botName) : entries.filter(b => b.active);
if (botName && targets.length === 0) {
console.error(`Could not find any bot named '${botName}' to reset.`);
process.exit(1);
}
console.log(`Setting regeneration trigger for ${targets.length} bot(s)...`);
for (const bot of targets) {
try {
const triggerFile = path.join(PROFILES_DIR, `recalculate.${bot.botKey}.trigger`);
fs.writeFileSync(triggerFile, '');
console.log(`✓ Trigger set for '${bot.name}' (${path.basename(triggerFile)})`);
} catch (err) {
console.warn(`Failed to set trigger for '${bot.name}': ${err.message}`);
}
}
console.log();
console.log('Action complete.');
console.log('- If the bot is running (CLI or PM2), it will detect the trigger and reset automatically.');
console.log('- If the bot is stopped, the grid will be regenerated the next time you run `dexbot start`.');
}
/**
* Export bot trading history and settings for QTradeX
* @param {string} botName - Bot name to export
*/
async function exportBotTrades(botName) {
if (!botName) {
console.error('Please specify a bot name: dexbot export <bot-name>');
process.exit(1);
}
try {
const exporter = require('./modules/order/export');
// Load bots configuration
const { config: botsData } = loadSettingsFile(PROFILES_BOTS_FILE);
const bot = resolveRawBotEntries(botsData).find((b) => b.name === botName);
if (!bot) {
console.error(`Bot '${botName}' not found in profiles/bots.json`);
process.exit(1);
}
console.log(`\n${'='.repeat(60)}`);
console.log(`Exporting bot: ${botName}`);
console.log(`${'='.repeat(60)}\n`);
// Create bot key from bot name (lowercase, replace spaces with hyphens)
const botKey = botName.toLowerCase().replace(/\s+/g, '-');
// Export trades and settings
const result = await exporter.exportBotTrades(botKey, bot, './exports');
if (result.success) {
console.log(`\n${'='.repeat(60)}`);
console.log(`✓ Export successful!`);
console.log(`${'='.repeat(60)}`);
console.log(`Bot: ${botName}`);
console.log(`Trades exported: ${result.trades_exported}`);
console.log(`CSV file: ${result.csv_path}`);
console.log(`Settings file: ${result.settings_path}`);
console.log(`Output directory: ${result.output_dir}`);
console.log(`Timestamp: ${result.timestamp}`);
console.log(`\nYou can now use these files with QTradeX for backtesting.\n`);
} else {
console.error(`\n✗ Export failed: ${result.error || 'Unknown error'}\n`);
process.exit(1);
}
} catch (err) {
console.error(`\nExport error: ${err.message}\n`);
process.exit(1);
}
}
/**
* Parse and execute CLI commands.
* Supported commands: start, drystart, reset, disable, keys, bots, pm2, update, export
* @returns {Promise<boolean>} True if a command was handled, false otherwise
*/
async function handleCLICommands() {
if (!cliArgs.length) return false;
const [command, target] = cliArgs;
if (!CLI_COMMANDS.includes(command)) {
console.error(`Unknown command '${command}'.`);
printCLIUsage();
process.exit(1);
}
switch (command) {
case 'start':
await startBotByName(target, { dryRun: false });
return true;
case 'drystart':
await startBotByName(target, { dryRun: true });
return true;
case 'reset':
await resetBotByName(target);
process.exit(0);
case 'disable':
await disableBotByName(target);
process.exit(0);
case 'keys':
await runAccountManager({ waitForConnection: true, exitAfter: true, disconnectAfter: true });
return true;
case 'bots':
setSuppressConnectionLog(true);
try {
await accountBots.main();
} finally {
try {
BitShares.disconnect();
} catch (err) {
console.warn('Failed to disconnect BitShares after bot helper exit:', err && err.message ? err.message : err);
}
}
process.exit(0);
return true;
case 'pm2':
try {
const pm2Launcher = require('./pm2.js');
await pm2Launcher.main();
// Close stdin and exit cleanly after PM2 startup
if (process.stdin) process.stdin.destroy();
process.exit(0);
} catch (err) {
console.error('Error:', err.message);
process.exit(1);
}
return true;
case 'update':
setSuppressConnectionLog(true);
require('./scripts/update.js');
return true;
case 'export':
setSuppressConnectionLog(true);
await exportBotTrades(target);
process.exit(0);
return true;
default:
printCLIUsage();
process.exit(1);
}
}
/**
* Run all bots marked as active in settings.
* @param {Object} [options={}] - Run options.
* @param {boolean} [options.forceDryRun=false] - Force dry-run mode.
* @param {string} [options.sourceName='settings'] - Source label.
* @returns {Promise<void>}
*/
async function runDefaultBots({ forceDryRun = false, sourceName = 'settings', launcherStyle = null } = {}) {
const { config } = loadSettingsFile(PROFILES_BOTS_FILE);
const entries = resolveRawBotEntries(config);
const normalized = normalizeBotEntries(entries);
await runBotInstances(normalized, { forceDryRun, sourceName, launcherStyle });
}
/**
* Main application entry point for DEXBot2 CLI.
* Handles initial setup, command routing, and starting active bots.
* @returns {Promise<void>}
*/
async function bootstrap() {
// Ensure profiles directory exists
const isNewSetup = ensureProfilesDirectory(PROFILES_DIR);
// If this is a new setup, prompt to set up keys
if (isNewSetup) {
// Suppress BitShares connection log during first-time setup
setSuppressConnectionLog(true);
console.log();
console.log('='.repeat(50));
console.log('Welcome to DEXBot2!');
console.log('='.repeat(50));
console.log();
// Generate default general.settings.json for new installations
const SETTINGS_FILE = path.join(PROFILES_DIR, 'general.settings.json');
const { LOG_LEVEL, GRID_LIMITS, TIMING, UPDATER, NODE_MANAGEMENT, MARKET_ADAPTER } = require('./modules/constants');
// Create a copy of GRID_LIMITS and remove any legacy fields if necessary
// (Though constants.js was already updated, this ensures a clean object)
const gridLimits = { ...GRID_LIMITS };
// Create NODES config from NODE_MANAGEMENT constants
const nodesConfig = {
enabled: false,
list: NODE_MANAGEMENT.DEFAULT_NODES,
healthCheck: {
enabled: true,
intervalMs: NODE_MANAGEMENT.HEALTH_CHECK_INTERVAL_MS,
timeoutMs: NODE_MANAGEMENT.HEALTH_CHECK_TIMEOUT_MS,
maxPingMs: NODE_MANAGEMENT.MAX_PING_MS,
blacklistThreshold: NODE_MANAGEMENT.BLACKLIST_THRESHOLD
},
selection: {
strategy: NODE_MANAGEMENT.SELECTION_STRATEGY,
preferredNode: null
}
};
const defaultSettings = {
LOG_LEVEL,
NODES: nodesConfig,
GRID_LIMITS: gridLimits,
TIMING: { ...TIMING },
UPDATER: { ...UPDATER },
MARKET_ADAPTER: { ...MARKET_ADAPTER },
};
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(defaultSettings, null, 2) + '\n', 'utf8');
console.log('✓ Created default general.settings.json');
console.log();
console.log('To get started, you need to configure your master password.');
console.log('This password will encrypt your private keys.');
console.log();
const setupKeys = readline.keyInYN('Set up master password now?');
if (setupKeys) {
console.log();
await chainKeys.main();
console.log();
console.log('Master password configured! Now you can:');
console.log(' node dexbot bots - Create and manage bots');
console.log(' node dexbot - Run your configured bots');
console.log();
} else {
console.log();
console.log('You can set up your master password later by running:');
console.log(' node dexbot keys');
console.log();
}
return;
}
// Handle CLI commands first (before checking for bots.json)
if (await handleCLICommands()) return;
// Check if bots.json exists - if not, guide user
if (!fs.existsSync(PROFILES_BOTS_FILE)) {
// Suppress BitShares connection log when no bots configured
setSuppressConnectionLog(true);
console.log();
console.log('No bot configuration found.');
console.log();
console.log('First, set up your master password:');
console.log(' node dexbot keys');
console.log();
console.log('Then, create your first bot:');
console.log(' node dexbot bots');
console.log();
process.exit(0);
}
await runDefaultBots();
}
function handleFatalBootstrapError(err) {
if (chainKeys.isMasterPasswordFailure(err)) {
printMasterPasswordFailure(err);
process.exit(1);
return;
} else if (err && err.message) {
console.error(err.message);
} else {
console.error(err);
}
try {
BitShares.disconnect();
} catch (disconnectErr) {
}
process.exit(1);
}
bootstrap().catch(handleFatalBootstrapError);