I’m working on a Solana trading bot that buys and sells tokens using the Jupiter API. The current implementation uses a fixed multiplier to determine the sell amount of tokens based on SOL. However, I want to make the sell amount more dynamic and based on the SOL value rather than a fixed multiplier. Below is the relevant part of the code:
Config.json is
{
"minTradeAmountSol": 1,
"maxTradeAmountSol": 5,
"maxTotalTradeAmountSol": 50,
"computeUnitPriceSol": 0.0001,
"jitoTipSol": 0.001,
"priorityFeeSol": 0.0002,
}
Typescript:
async function executeSwap() {
if (totalTradedAmount >= maxTotalTradeAmount) {
console.log('Max trade amount reached. Stopping bot.');
process.exit(0);
}
// Randomly select a wallet for this trade
const wallet = wallets[Math.floor(Math.random() * wallets.length)];
console.log('Using wallet:', wallet.publicKey.toBase58());
// Randomly decide whether to buy or sell
const isBuy = Math.random() < 0.5;
// Randomly select trade amount between min and max
let tradeAmount = Math.floor(Math.random() * (maxTradeAmount - minTradeAmount + 1)) + minTradeAmount;
console.log(`Trade Amount (lamports): ${tradeAmount}`);
console.log(`Trade Amount (tokens): ${(tradeAmount / lamportsPerSol).toFixed(tokenDecimals)} tokens`);
const inputMint = isBuy ? config.tradeInputToken : config.tradeOutputToken;
const outputMint = isBuy ? config.tradeOutputToken : config.tradeInputToken;
// Adjust sell amount (e.g., multiply by 1000000)
if (!isBuy) {
tradeAmount *= 1000000; // Adjust this multiplier based on your needs
console.log(`Adjusted Sell Amount (lamports): ${tradeAmount}`);
console.log(`Adjusted Sell Amount (tokens): ${(tradeAmount / lamportsPerSol).toFixed(tokenDecimals)} tokens`);
}
if (!Number.isInteger(tradeAmount)) {
console.error('Error: Trade amount is not a valid integer.');
return;
}
// Get a quote for the swap using Jupiter API
const quoteResponse = await (
await fetch(`https://jupiter-swap-api.quiknode.pro/8E170C166412/quote?inputMint=${inputMint}&outputMint=${outputMint}&amount=${tradeAmount}&slippageBps=50`)
).json();
if (quoteResponse.error) {
console.error('Error in Quote:', quoteResponse.error);
return;
}
console.log(`Received Quote for ${isBuy ? 'Buy' : 'Sell'}:`, quoteResponse);
const response = await fetch('https://jupiter-swap-api.quiknode.pro/8E170C166412/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
quoteResponse,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: false,
dynamicComputeUnitLimit: true,
computeUnitPriceMicroLamports, // Use converted compute unit price
prioritizationFeeLamports: config.prioritizationFeeLamports, // Priority fees in lamports
jitoTipLamports: config.jitoTipLamports // Jito tip in lamports
}),
});
const { swapTransaction } = await response.json();
if (!swapTransaction) {
throw new Error('Swap transaction is undefined or empty');
}
const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
transaction.sign([wallet.payer]);
const latestBlockHash = await connection.getLatestBlockhash();
const rawTransaction = transaction.serialize();
try {
const txid = await connection.sendRawTransaction(rawTransaction, {
skipPreflight: true,
maxRetries: 2,
});
await connection.confirmTransaction({
signature: txid,
blockhash: latestBlockHash.blockhash,
lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
});
console.log(`Transaction successful: https://solscan.io/tx/${txid}`);
totalTradedAmount += quoteResponse.amount;
} catch (error: any) {
if (error.message.includes("TransactionExpiredBlockheightExceededError")) {
console.error("Transaction expired due to block height exceeding the limit. Retrying...");
await executeSwap(); // Retry the transaction
} else {
console.error("Error during swap execution:", error.message);
}
}
}
Currently, the sell amount is adjusted using a fixed multiplier (tradeAmount *= 1000000
). I want to adjust this so that the sell amount of tokens is directly calculated based on the SOL value without relying on this multiplier.
Is there a way to calculate the sell amount dynamically based on the SOL amount in a more flexible way? Should I introduce min and max token amounts in my config and calculate the sell amount accordingly?
Also jito tip not working here.
Any suggestions or best practices would be greatly appreciated!
Sky Update is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.